From 1f089c39ab53dfbfa347796d70eab724bc5c7840 Mon Sep 17 00:00:00 2001 From: CryptoCentric Date: Wed, 17 Apr 2019 11:59:30 +0100 Subject: [PATCH 001/282] Clean Remove unsed Rev1 Code Remove Rev1 as its never been used --- src/crypto/Lyra2RE/Lyra2RE.c | 30 ------------------------------ src/crypto/Lyra2RE/Lyra2RE.h | 1 - 2 files changed, 31 deletions(-) diff --git a/src/crypto/Lyra2RE/Lyra2RE.c b/src/crypto/Lyra2RE/Lyra2RE.c index 4c0afc06ca3a..e252991bd7b0 100644 --- a/src/crypto/Lyra2RE/Lyra2RE.c +++ b/src/crypto/Lyra2RE/Lyra2RE.c @@ -40,36 +40,6 @@ #include "sph_skein.h" #include "Lyra2.h" -void lyra2re_hash(const char* input, char* output) -{ - sph_blake256_context ctx_blake; - sph_groestl256_context ctx_groestl; - sph_keccak256_context ctx_keccak; - sph_skein256_context ctx_skein; - - uint32_t hashA[8], hashB[8]; - - sph_blake256_init(&ctx_blake); - sph_blake256 (&ctx_blake, input, 80); - sph_blake256_close (&ctx_blake, hashA); - - sph_keccak256_init(&ctx_keccak); - sph_keccak256 (&ctx_keccak,hashA, 32); - sph_keccak256_close(&ctx_keccak, hashB); - - LYRA2_old(hashA, 32, hashB, 32, hashB, 32, 1, 8, 8); - - sph_skein256_init(&ctx_skein); - sph_skein256 (&ctx_skein, hashA, 32); - sph_skein256_close(&ctx_skein, hashB); - - sph_groestl256_init(&ctx_groestl); - sph_groestl256 (&ctx_groestl, hashB, 32); - sph_groestl256_close(&ctx_groestl, hashA); - - memcpy(output, hashA, 32); -} - void lyra2re2_hash(const char* input, char* output) { sph_blake256_context ctx_blake; diff --git a/src/crypto/Lyra2RE/Lyra2RE.h b/src/crypto/Lyra2RE/Lyra2RE.h index 77bcbe414bbb..467176d2a188 100644 --- a/src/crypto/Lyra2RE/Lyra2RE.h +++ b/src/crypto/Lyra2RE/Lyra2RE.h @@ -5,7 +5,6 @@ extern "C" { #endif -void lyra2re_hash(const char* input, char* output); void lyra2re2_hash(const char* input, char* output); #ifdef __cplusplus From 8b1e31fcdba64d9eab1e601cc35c72e58d4c002d Mon Sep 17 00:00:00 2001 From: CryptoCentric Date: Wed, 17 Apr 2019 13:26:50 +0100 Subject: [PATCH 002/282] Cleanup Crypto Hash Source --- src/Makefile.am | 46 +- src/bench/crypto_hash.cpp | 80 - src/crypto/Lyra2RE/bmw.c | 8 + src/crypto/Lyra2RE/cubehash.c | 6 + src/crypto/{ => Lyra2RE}/echo.c | 0 src/crypto/Lyra2RE/groestl.c | 6 +- src/crypto/{ => Lyra2RE}/shavite.c | 0 src/crypto/{ => Lyra2RE}/simd.c | 0 src/crypto/Lyra2RE/sph_blake.h | 2 +- src/crypto/Lyra2RE/sph_bmw.h | 8 + src/crypto/Lyra2RE/sph_cubehash.h | 7 + src/crypto/{ => Lyra2RE}/sph_echo.h | 0 src/crypto/Lyra2RE/sph_groestl.h | 2 +- src/crypto/{ => Lyra2RE}/sph_jh.h | 0 src/crypto/Lyra2RE/sph_keccak.h | 2 +- src/crypto/{ => Lyra2RE}/sph_luffa.h | 0 src/crypto/{ => Lyra2RE}/sph_shavite.h | 0 src/crypto/{ => Lyra2RE}/sph_simd.h | 0 src/crypto/Lyra2RE/sph_skein.h | 2 +- src/crypto/Lyra2RE/sph_types.h | 2 +- src/crypto/blake.c | 1120 --------- src/crypto/bmw.c | 965 -------- src/crypto/cubehash.c | 723 ------ src/crypto/groestl.c | 3123 ------------------------ src/crypto/skein.c | 1254 ---------- src/crypto/sph_blake.h | 327 --- src/crypto/sph_bmw.h | 328 --- src/crypto/sph_cubehash.h | 292 --- src/crypto/sph_groestl.h | 329 --- src/crypto/sph_keccak.h | 293 --- src/crypto/sph_skein.h | 298 --- src/crypto/sph_types.h | 1976 --------------- src/hash.h | 89 +- 33 files changed, 65 insertions(+), 11223 deletions(-) rename src/crypto/{ => Lyra2RE}/echo.c (100%) rename src/crypto/{ => Lyra2RE}/shavite.c (100%) rename src/crypto/{ => Lyra2RE}/simd.c (100%) rename src/crypto/{ => Lyra2RE}/sph_echo.h (100%) rename src/crypto/{ => Lyra2RE}/sph_jh.h (100%) rename src/crypto/{ => Lyra2RE}/sph_luffa.h (100%) rename src/crypto/{ => Lyra2RE}/sph_shavite.h (100%) rename src/crypto/{ => Lyra2RE}/sph_simd.h (100%) delete mode 100644 src/crypto/blake.c delete mode 100644 src/crypto/bmw.c delete mode 100644 src/crypto/cubehash.c delete mode 100644 src/crypto/groestl.c delete mode 100644 src/crypto/skein.c delete mode 100644 src/crypto/sph_blake.h delete mode 100644 src/crypto/sph_bmw.h delete mode 100644 src/crypto/sph_cubehash.h delete mode 100644 src/crypto/sph_groestl.h delete mode 100644 src/crypto/sph_keccak.h delete mode 100644 src/crypto/sph_skein.h delete mode 100644 src/crypto/sph_types.h diff --git a/src/Makefile.am b/src/Makefile.am index 382b71d160cb..7456285e50d7 100644 --- a/src/Makefile.am +++ b/src/Makefile.am @@ -320,44 +320,28 @@ crypto_libabsolute_crypto_a_SOURCES = \ crypto/Lyra2RE/Sponge.c \ crypto/Lyra2RE/Sponge.h \ crypto/Lyra2RE/sph_blake.h \ - crypto/Lyra2RE/sph_bmw.h \ - crypto/Lyra2RE/sph_cubehash.h \ crypto/Lyra2RE/sph_groestl.h \ crypto/Lyra2RE/sph_keccak.h \ crypto/Lyra2RE/sph_skein.h \ crypto/Lyra2RE/sph_types.h \ + crypto/Lyra2RE/sph_cubehash.h \ crypto/Lyra2RE/blake.c \ - crypto/Lyra2RE/groestl.c \ crypto/Lyra2RE/keccak.c \ - crypto/Lyra2RE/skein.c \ + crypto/Lyra2RE/skein.c + crypto/Lyra2RE/bmw.c \ crypto/Lyra2RE/cubehash.c \ - crypto/Lyra2RE/bmw.c - -# x11 -crypto_libabsolute_crypto_a_SOURCES += \ - crypto/blake.c \ - crypto/bmw.c \ - crypto/cubehash.c \ - crypto/echo.c \ - crypto/groestl.c \ - crypto/jh.c \ - crypto/keccak.c \ - crypto/luffa.c \ - crypto/shavite.c \ - crypto/simd.c \ - crypto/skein.c \ - crypto/sph_blake.h \ - crypto/sph_bmw.h \ - crypto/sph_cubehash.h \ - crypto/sph_echo.h \ - crypto/sph_groestl.h \ - crypto/sph_jh.h \ - crypto/sph_keccak.h \ - crypto/sph_luffa.h \ - crypto/sph_shavite.h \ - crypto/sph_simd.h \ - crypto/sph_skein.h \ - crypto/sph_types.h + crypto/Lyra2RE/echo.c \ + crypto/Lyra2RE/groestl.c \ + crypto/Lyra2RE/jh.c \ + crypto/Lyra2RE/luffa.c \ + crypto/Lyra2RE/shavite.c \ + crypto/Lyra2RE/simd.c \ + crypto/Lyra2RE/sph_bmw.h \ + crypto/Lyra2RE/sph_echo.h \ + crypto/Lyra2RE/sph_jh.h \ + crypto/Lyra2RE/sph_luffa.h \ + crypto/Lyra2RE/sph_shavite.h \ + crypto/Lyra2RE/sph_simd.h # consensus: shared between all executables that validate any consensus rules. libabsolute_consensus_a_CPPFLAGS = $(AM_CPPFLAGS) $(BITCOIN_INCLUDES) diff --git a/src/bench/crypto_hash.cpp b/src/bench/crypto_hash.cpp index 7f9b47143bfe..3865509ca3ac 100644 --- a/src/bench/crypto_hash.cpp +++ b/src/bench/crypto_hash.cpp @@ -130,83 +130,3 @@ static void HASH_DSHA256_2048b_single(benchmark::State& state) while (state.KeepRunning()) CHash256().Write(in.data(), in.size()).Finalize(&in[0]); } - -static void HASH_X11(benchmark::State& state) -{ - uint256 hash; - std::vector in(BUFFER_SIZE,0); - while (state.KeepRunning()) - hash = HashX11(in.begin(), in.end()); -} - -static void HASH_X11_0032b_single(benchmark::State& state) -{ - uint256 hash; - std::vector in(32,0); - while (state.KeepRunning()) - hash = HashX11(in.begin(), in.end()); -} - -static void HASH_X11_0080b_single(benchmark::State& state) -{ - uint256 hash; - std::vector in(80,0); - while (state.KeepRunning()) - hash = HashX11(in.begin(), in.end()); -} - -static void HASH_X11_0128b_single(benchmark::State& state) -{ - uint256 hash; - std::vector in(128,0); - while (state.KeepRunning()) - hash = HashX11(in.begin(), in.end()); -} - -static void HASH_X11_0512b_single(benchmark::State& state) -{ - uint256 hash; - std::vector in(512,0); - while (state.KeepRunning()) - hash = HashX11(in.begin(), in.end()); -} - -static void HASH_X11_1024b_single(benchmark::State& state) -{ - uint256 hash; - std::vector in(1024,0); - while (state.KeepRunning()) - hash = HashX11(in.begin(), in.end()); -} - -static void HASH_X11_2048b_single(benchmark::State& state) -{ - uint256 hash; - std::vector in(2048,0); - while (state.KeepRunning()) - hash = HashX11(in.begin(), in.end()); -} - -BENCHMARK(HASH_RIPEMD160); -BENCHMARK(HASH_SHA1); -BENCHMARK(HASH_SHA256); -BENCHMARK(HASH_DSHA256); -BENCHMARK(HASH_SHA512); -BENCHMARK(HASH_X11); - -BENCHMARK(HASH_SHA256_0032b); -BENCHMARK(HASH_DSHA256_0032b); -BENCHMARK(HASH_SipHash_0032b); - -BENCHMARK(HASH_DSHA256_0032b_single); -BENCHMARK(HASH_DSHA256_0080b_single); -BENCHMARK(HASH_DSHA256_0128b_single); -BENCHMARK(HASH_DSHA256_0512b_single); -BENCHMARK(HASH_DSHA256_1024b_single); -BENCHMARK(HASH_DSHA256_2048b_single); -BENCHMARK(HASH_X11_0032b_single); -BENCHMARK(HASH_X11_0080b_single); -BENCHMARK(HASH_X11_0128b_single); -BENCHMARK(HASH_X11_0512b_single); -BENCHMARK(HASH_X11_1024b_single); -BENCHMARK(HASH_X11_2048b_single); diff --git a/src/crypto/Lyra2RE/bmw.c b/src/crypto/Lyra2RE/bmw.c index 718191d0e20b..b89a881e80c8 100644 --- a/src/crypto/Lyra2RE/bmw.c +++ b/src/crypto/Lyra2RE/bmw.c @@ -34,6 +34,10 @@ #include #include +#ifdef __cplusplus +extern "C"{ +#endif + #include "sph_bmw.h" #if SPH_SMALL_FOOTPRINT && !defined SPH_SMALL_FOOTPRINT_BMW @@ -955,3 +959,7 @@ sph_bmw512_addbits_and_close(void *cc, unsigned ub, unsigned n, void *dst) } #endif + +#ifdef __cplusplus +} +#endif diff --git a/src/crypto/Lyra2RE/cubehash.c b/src/crypto/Lyra2RE/cubehash.c index f993c05b3523..9322fe14e055 100644 --- a/src/crypto/Lyra2RE/cubehash.c +++ b/src/crypto/Lyra2RE/cubehash.c @@ -35,6 +35,9 @@ #include #include "sph_cubehash.h" +#ifdef __cplusplus +extern "C"{ +#endif #if SPH_SMALL_FOOTPRINT && !defined SPH_SMALL_FOOTPRINT_CUBEHASH #define SPH_SMALL_FOOTPRINT_CUBEHASH 1 @@ -715,3 +718,6 @@ sph_cubehash512_addbits_and_close(void *cc, unsigned ub, unsigned n, void *dst) cubehash_close(cc, ub, n, dst, 16); sph_cubehash512_init(cc); } +#ifdef __cplusplus +} +#endif diff --git a/src/crypto/echo.c b/src/crypto/Lyra2RE/echo.c similarity index 100% rename from src/crypto/echo.c rename to src/crypto/Lyra2RE/echo.c diff --git a/src/crypto/Lyra2RE/groestl.c b/src/crypto/Lyra2RE/groestl.c index aa0d1186ef42..928bc41efab9 100644 --- a/src/crypto/Lyra2RE/groestl.c +++ b/src/crypto/Lyra2RE/groestl.c @@ -2813,6 +2813,7 @@ static void groestl_small_close(sph_groestl_small_context *sc, unsigned ub, unsigned n, void *dst, size_t out_len) { + unsigned char *buf; unsigned char pad[72]; size_t u, ptr, pad_len; #if SPH_64 @@ -2823,6 +2824,7 @@ groestl_small_close(sph_groestl_small_context *sc, unsigned z; DECL_STATE_SMALL + buf = sc->buf; ptr = sc->ptr; z = 0x80 >> n; pad[0] = ((ub & -z) | z) & 0xFF; @@ -2947,6 +2949,7 @@ static void groestl_big_close(sph_groestl_big_context *sc, unsigned ub, unsigned n, void *dst, size_t out_len) { + unsigned char *buf; unsigned char pad[136]; size_t ptr, pad_len, u; #if SPH_64 @@ -2957,6 +2960,7 @@ groestl_big_close(sph_groestl_big_context *sc, unsigned z; DECL_STATE_BIG + buf = sc->buf; ptr = sc->ptr; z = 0x80 >> n; pad[0] = ((ub & -z) | z) & 0xFF; @@ -3116,4 +3120,4 @@ sph_groestl512_addbits_and_close(void *cc, unsigned ub, unsigned n, void *dst) #ifdef __cplusplus } -#endif \ No newline at end of file +#endif diff --git a/src/crypto/shavite.c b/src/crypto/Lyra2RE/shavite.c similarity index 100% rename from src/crypto/shavite.c rename to src/crypto/Lyra2RE/shavite.c diff --git a/src/crypto/simd.c b/src/crypto/Lyra2RE/simd.c similarity index 100% rename from src/crypto/simd.c rename to src/crypto/Lyra2RE/simd.c diff --git a/src/crypto/Lyra2RE/sph_blake.h b/src/crypto/Lyra2RE/sph_blake.h index 1f8f8fa1521f..d8d794399d00 100644 --- a/src/crypto/Lyra2RE/sph_blake.h +++ b/src/crypto/Lyra2RE/sph_blake.h @@ -324,4 +324,4 @@ void sph_blake512_addbits_and_close( } #endif -#endif \ No newline at end of file +#endif diff --git a/src/crypto/Lyra2RE/sph_bmw.h b/src/crypto/Lyra2RE/sph_bmw.h index 484a2a745489..d386b0c14053 100644 --- a/src/crypto/Lyra2RE/sph_bmw.h +++ b/src/crypto/Lyra2RE/sph_bmw.h @@ -36,6 +36,10 @@ #ifndef SPH_BMW_H__ #define SPH_BMW_H__ +#ifdef __cplusplus +extern "C"{ +#endif + #include #include "sph_types.h" @@ -317,4 +321,8 @@ void sph_bmw512_addbits_and_close( #endif +#ifdef __cplusplus +} +#endif + #endif diff --git a/src/crypto/Lyra2RE/sph_cubehash.h b/src/crypto/Lyra2RE/sph_cubehash.h index c66367480e12..487a1946ad40 100644 --- a/src/crypto/Lyra2RE/sph_cubehash.h +++ b/src/crypto/Lyra2RE/sph_cubehash.h @@ -37,6 +37,10 @@ #ifndef SPH_CUBEHASH_H__ #define SPH_CUBEHASH_H__ +#ifdef __cplusplus +extern "C"{ +#endif + #include #include "sph_types.h" @@ -281,5 +285,8 @@ void sph_cubehash512_close(void *cc, void *dst); */ void sph_cubehash512_addbits_and_close( void *cc, unsigned ub, unsigned n, void *dst); +#ifdef __cplusplus +} +#endif #endif diff --git a/src/crypto/sph_echo.h b/src/crypto/Lyra2RE/sph_echo.h similarity index 100% rename from src/crypto/sph_echo.h rename to src/crypto/Lyra2RE/sph_echo.h diff --git a/src/crypto/Lyra2RE/sph_groestl.h b/src/crypto/Lyra2RE/sph_groestl.h index 45b5923b8e35..495f05e21174 100644 --- a/src/crypto/Lyra2RE/sph_groestl.h +++ b/src/crypto/Lyra2RE/sph_groestl.h @@ -326,4 +326,4 @@ void sph_groestl512_addbits_and_close( } #endif -#endif \ No newline at end of file +#endif diff --git a/src/crypto/sph_jh.h b/src/crypto/Lyra2RE/sph_jh.h similarity index 100% rename from src/crypto/sph_jh.h rename to src/crypto/Lyra2RE/sph_jh.h diff --git a/src/crypto/Lyra2RE/sph_keccak.h b/src/crypto/Lyra2RE/sph_keccak.h index 4e9586b7d314..bdafdb88db02 100644 --- a/src/crypto/Lyra2RE/sph_keccak.h +++ b/src/crypto/Lyra2RE/sph_keccak.h @@ -290,4 +290,4 @@ void sph_keccak512_addbits_and_close( } #endif -#endif \ No newline at end of file +#endif diff --git a/src/crypto/sph_luffa.h b/src/crypto/Lyra2RE/sph_luffa.h similarity index 100% rename from src/crypto/sph_luffa.h rename to src/crypto/Lyra2RE/sph_luffa.h diff --git a/src/crypto/sph_shavite.h b/src/crypto/Lyra2RE/sph_shavite.h similarity index 100% rename from src/crypto/sph_shavite.h rename to src/crypto/Lyra2RE/sph_shavite.h diff --git a/src/crypto/sph_simd.h b/src/crypto/Lyra2RE/sph_simd.h similarity index 100% rename from src/crypto/sph_simd.h rename to src/crypto/Lyra2RE/sph_simd.h diff --git a/src/crypto/Lyra2RE/sph_skein.h b/src/crypto/Lyra2RE/sph_skein.h index e045956f6b9a..bddbc86fa5aa 100644 --- a/src/crypto/Lyra2RE/sph_skein.h +++ b/src/crypto/Lyra2RE/sph_skein.h @@ -295,4 +295,4 @@ void sph_skein512_addbits_and_close( } #endif -#endif \ No newline at end of file +#endif diff --git a/src/crypto/Lyra2RE/sph_types.h b/src/crypto/Lyra2RE/sph_types.h index 56a314cdb8f1..7295b0b37097 100644 --- a/src/crypto/Lyra2RE/sph_types.h +++ b/src/crypto/Lyra2RE/sph_types.h @@ -1973,4 +1973,4 @@ sph_dec64le_aligned(const void *src) #endif /* Doxygen excluded block */ -#endif \ No newline at end of file +#endif diff --git a/src/crypto/blake.c b/src/crypto/blake.c deleted file mode 100644 index 0650b9cf21e0..000000000000 --- a/src/crypto/blake.c +++ /dev/null @@ -1,1120 +0,0 @@ -/* $Id: blake.c 252 2011-06-07 17:55:14Z tp $ */ -/* - * BLAKE implementation. - * - * ==========================(LICENSE BEGIN)============================ - * - * Copyright (c) 2007-2010 Projet RNRT SAPHIR - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY - * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, - * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE - * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - * ===========================(LICENSE END)============================= - * - * @author Thomas Pornin - */ - -#include -#include -#include - -#include "sph_blake.h" - -#ifdef __cplusplus -extern "C"{ -#endif - -#if SPH_SMALL_FOOTPRINT && !defined SPH_SMALL_FOOTPRINT_BLAKE -#define SPH_SMALL_FOOTPRINT_BLAKE 1 -#endif - -#if SPH_SMALL_FOOTPRINT_BLAKE -#define SPH_COMPACT_BLAKE_32 1 -#endif - -#if SPH_64 && (SPH_SMALL_FOOTPRINT_BLAKE || !SPH_64_TRUE) -#define SPH_COMPACT_BLAKE_64 1 -#endif - -#ifdef _MSC_VER -#pragma warning (disable: 4146) -#endif - -static const sph_u32 IV224[8] = { - SPH_C32(0xC1059ED8), SPH_C32(0x367CD507), - SPH_C32(0x3070DD17), SPH_C32(0xF70E5939), - SPH_C32(0xFFC00B31), SPH_C32(0x68581511), - SPH_C32(0x64F98FA7), SPH_C32(0xBEFA4FA4) -}; - -static const sph_u32 IV256[8] = { - SPH_C32(0x6A09E667), SPH_C32(0xBB67AE85), - SPH_C32(0x3C6EF372), SPH_C32(0xA54FF53A), - SPH_C32(0x510E527F), SPH_C32(0x9B05688C), - SPH_C32(0x1F83D9AB), SPH_C32(0x5BE0CD19) -}; - -#if SPH_64 - -static const sph_u64 IV384[8] = { - SPH_C64(0xCBBB9D5DC1059ED8), SPH_C64(0x629A292A367CD507), - SPH_C64(0x9159015A3070DD17), SPH_C64(0x152FECD8F70E5939), - SPH_C64(0x67332667FFC00B31), SPH_C64(0x8EB44A8768581511), - SPH_C64(0xDB0C2E0D64F98FA7), SPH_C64(0x47B5481DBEFA4FA4) -}; - -static const sph_u64 IV512[8] = { - SPH_C64(0x6A09E667F3BCC908), SPH_C64(0xBB67AE8584CAA73B), - SPH_C64(0x3C6EF372FE94F82B), SPH_C64(0xA54FF53A5F1D36F1), - SPH_C64(0x510E527FADE682D1), SPH_C64(0x9B05688C2B3E6C1F), - SPH_C64(0x1F83D9ABFB41BD6B), SPH_C64(0x5BE0CD19137E2179) -}; - -#endif - -#if SPH_COMPACT_BLAKE_32 || SPH_COMPACT_BLAKE_64 - -static const unsigned sigma[16][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 }, - { 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 } -}; - -/* - 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 -*/ -#endif - -#define Z00 0 -#define Z01 1 -#define Z02 2 -#define Z03 3 -#define Z04 4 -#define Z05 5 -#define Z06 6 -#define Z07 7 -#define Z08 8 -#define Z09 9 -#define Z0A A -#define Z0B B -#define Z0C C -#define Z0D D -#define Z0E E -#define Z0F F - -#define Z10 E -#define Z11 A -#define Z12 4 -#define Z13 8 -#define Z14 9 -#define Z15 F -#define Z16 D -#define Z17 6 -#define Z18 1 -#define Z19 C -#define Z1A 0 -#define Z1B 2 -#define Z1C B -#define Z1D 7 -#define Z1E 5 -#define Z1F 3 - -#define Z20 B -#define Z21 8 -#define Z22 C -#define Z23 0 -#define Z24 5 -#define Z25 2 -#define Z26 F -#define Z27 D -#define Z28 A -#define Z29 E -#define Z2A 3 -#define Z2B 6 -#define Z2C 7 -#define Z2D 1 -#define Z2E 9 -#define Z2F 4 - -#define Z30 7 -#define Z31 9 -#define Z32 3 -#define Z33 1 -#define Z34 D -#define Z35 C -#define Z36 B -#define Z37 E -#define Z38 2 -#define Z39 6 -#define Z3A 5 -#define Z3B A -#define Z3C 4 -#define Z3D 0 -#define Z3E F -#define Z3F 8 - -#define Z40 9 -#define Z41 0 -#define Z42 5 -#define Z43 7 -#define Z44 2 -#define Z45 4 -#define Z46 A -#define Z47 F -#define Z48 E -#define Z49 1 -#define Z4A B -#define Z4B C -#define Z4C 6 -#define Z4D 8 -#define Z4E 3 -#define Z4F D - -#define Z50 2 -#define Z51 C -#define Z52 6 -#define Z53 A -#define Z54 0 -#define Z55 B -#define Z56 8 -#define Z57 3 -#define Z58 4 -#define Z59 D -#define Z5A 7 -#define Z5B 5 -#define Z5C F -#define Z5D E -#define Z5E 1 -#define Z5F 9 - -#define Z60 C -#define Z61 5 -#define Z62 1 -#define Z63 F -#define Z64 E -#define Z65 D -#define Z66 4 -#define Z67 A -#define Z68 0 -#define Z69 7 -#define Z6A 6 -#define Z6B 3 -#define Z6C 9 -#define Z6D 2 -#define Z6E 8 -#define Z6F B - -#define Z70 D -#define Z71 B -#define Z72 7 -#define Z73 E -#define Z74 C -#define Z75 1 -#define Z76 3 -#define Z77 9 -#define Z78 5 -#define Z79 0 -#define Z7A F -#define Z7B 4 -#define Z7C 8 -#define Z7D 6 -#define Z7E 2 -#define Z7F A - -#define Z80 6 -#define Z81 F -#define Z82 E -#define Z83 9 -#define Z84 B -#define Z85 3 -#define Z86 0 -#define Z87 8 -#define Z88 C -#define Z89 2 -#define Z8A D -#define Z8B 7 -#define Z8C 1 -#define Z8D 4 -#define Z8E A -#define Z8F 5 - -#define Z90 A -#define Z91 2 -#define Z92 8 -#define Z93 4 -#define Z94 7 -#define Z95 6 -#define Z96 1 -#define Z97 5 -#define Z98 F -#define Z99 B -#define Z9A 9 -#define Z9B E -#define Z9C 3 -#define Z9D C -#define Z9E D -#define Z9F 0 - -#define Mx(r, i) Mx_(Z ## r ## i) -#define Mx_(n) Mx__(n) -#define Mx__(n) M ## n - -#define CSx(r, i) CSx_(Z ## r ## i) -#define CSx_(n) CSx__(n) -#define CSx__(n) CS ## n - -#define CS0 SPH_C32(0x243F6A88) -#define CS1 SPH_C32(0x85A308D3) -#define CS2 SPH_C32(0x13198A2E) -#define CS3 SPH_C32(0x03707344) -#define CS4 SPH_C32(0xA4093822) -#define CS5 SPH_C32(0x299F31D0) -#define CS6 SPH_C32(0x082EFA98) -#define CS7 SPH_C32(0xEC4E6C89) -#define CS8 SPH_C32(0x452821E6) -#define CS9 SPH_C32(0x38D01377) -#define CSA SPH_C32(0xBE5466CF) -#define CSB SPH_C32(0x34E90C6C) -#define CSC SPH_C32(0xC0AC29B7) -#define CSD SPH_C32(0xC97C50DD) -#define CSE SPH_C32(0x3F84D5B5) -#define CSF SPH_C32(0xB5470917) - -#if SPH_COMPACT_BLAKE_32 - -static const sph_u32 CS[16] = { - SPH_C32(0x243F6A88), SPH_C32(0x85A308D3), - SPH_C32(0x13198A2E), SPH_C32(0x03707344), - SPH_C32(0xA4093822), SPH_C32(0x299F31D0), - SPH_C32(0x082EFA98), SPH_C32(0xEC4E6C89), - SPH_C32(0x452821E6), SPH_C32(0x38D01377), - SPH_C32(0xBE5466CF), SPH_C32(0x34E90C6C), - SPH_C32(0xC0AC29B7), SPH_C32(0xC97C50DD), - SPH_C32(0x3F84D5B5), SPH_C32(0xB5470917) -}; - -#endif - -#if SPH_64 - -#define CBx(r, i) CBx_(Z ## r ## i) -#define CBx_(n) CBx__(n) -#define CBx__(n) CB ## n - -#define CB0 SPH_C64(0x243F6A8885A308D3) -#define CB1 SPH_C64(0x13198A2E03707344) -#define CB2 SPH_C64(0xA4093822299F31D0) -#define CB3 SPH_C64(0x082EFA98EC4E6C89) -#define CB4 SPH_C64(0x452821E638D01377) -#define CB5 SPH_C64(0xBE5466CF34E90C6C) -#define CB6 SPH_C64(0xC0AC29B7C97C50DD) -#define CB7 SPH_C64(0x3F84D5B5B5470917) -#define CB8 SPH_C64(0x9216D5D98979FB1B) -#define CB9 SPH_C64(0xD1310BA698DFB5AC) -#define CBA SPH_C64(0x2FFD72DBD01ADFB7) -#define CBB SPH_C64(0xB8E1AFED6A267E96) -#define CBC SPH_C64(0xBA7C9045F12C7F99) -#define CBD SPH_C64(0x24A19947B3916CF7) -#define CBE SPH_C64(0x0801F2E2858EFC16) -#define CBF SPH_C64(0x636920D871574E69) - -#if SPH_COMPACT_BLAKE_64 - -static const sph_u64 CB[16] = { - SPH_C64(0x243F6A8885A308D3), SPH_C64(0x13198A2E03707344), - SPH_C64(0xA4093822299F31D0), SPH_C64(0x082EFA98EC4E6C89), - SPH_C64(0x452821E638D01377), SPH_C64(0xBE5466CF34E90C6C), - SPH_C64(0xC0AC29B7C97C50DD), SPH_C64(0x3F84D5B5B5470917), - SPH_C64(0x9216D5D98979FB1B), SPH_C64(0xD1310BA698DFB5AC), - SPH_C64(0x2FFD72DBD01ADFB7), SPH_C64(0xB8E1AFED6A267E96), - SPH_C64(0xBA7C9045F12C7F99), SPH_C64(0x24A19947B3916CF7), - SPH_C64(0x0801F2E2858EFC16), SPH_C64(0x636920D871574E69) -}; - -#endif - -#endif - -#define GS(m0, m1, c0, c1, a, b, c, d) do { \ - a = SPH_T32(a + b + (m0 ^ c1)); \ - d = SPH_ROTR32(d ^ a, 16); \ - c = SPH_T32(c + d); \ - b = SPH_ROTR32(b ^ c, 12); \ - a = SPH_T32(a + b + (m1 ^ c0)); \ - d = SPH_ROTR32(d ^ a, 8); \ - c = SPH_T32(c + d); \ - b = SPH_ROTR32(b ^ c, 7); \ - } while (0) - -#if SPH_COMPACT_BLAKE_32 - -#define ROUND_S(r) do { \ - GS(M[sigma[r][0x0]], M[sigma[r][0x1]], \ - CS[sigma[r][0x0]], CS[sigma[r][0x1]], V0, V4, V8, VC); \ - GS(M[sigma[r][0x2]], M[sigma[r][0x3]], \ - CS[sigma[r][0x2]], CS[sigma[r][0x3]], V1, V5, V9, VD); \ - GS(M[sigma[r][0x4]], M[sigma[r][0x5]], \ - CS[sigma[r][0x4]], CS[sigma[r][0x5]], V2, V6, VA, VE); \ - GS(M[sigma[r][0x6]], M[sigma[r][0x7]], \ - CS[sigma[r][0x6]], CS[sigma[r][0x7]], V3, V7, VB, VF); \ - GS(M[sigma[r][0x8]], M[sigma[r][0x9]], \ - CS[sigma[r][0x8]], CS[sigma[r][0x9]], V0, V5, VA, VF); \ - GS(M[sigma[r][0xA]], M[sigma[r][0xB]], \ - CS[sigma[r][0xA]], CS[sigma[r][0xB]], V1, V6, VB, VC); \ - GS(M[sigma[r][0xC]], M[sigma[r][0xD]], \ - CS[sigma[r][0xC]], CS[sigma[r][0xD]], V2, V7, V8, VD); \ - GS(M[sigma[r][0xE]], M[sigma[r][0xF]], \ - CS[sigma[r][0xE]], CS[sigma[r][0xF]], V3, V4, V9, VE); \ - } while (0) - -#else - -#define ROUND_S(r) do { \ - GS(Mx(r, 0), Mx(r, 1), CSx(r, 0), CSx(r, 1), V0, V4, V8, VC); \ - GS(Mx(r, 2), Mx(r, 3), CSx(r, 2), CSx(r, 3), V1, V5, V9, VD); \ - GS(Mx(r, 4), Mx(r, 5), CSx(r, 4), CSx(r, 5), V2, V6, VA, VE); \ - GS(Mx(r, 6), Mx(r, 7), CSx(r, 6), CSx(r, 7), V3, V7, VB, VF); \ - GS(Mx(r, 8), Mx(r, 9), CSx(r, 8), CSx(r, 9), V0, V5, VA, VF); \ - GS(Mx(r, A), Mx(r, B), CSx(r, A), CSx(r, B), V1, V6, VB, VC); \ - GS(Mx(r, C), Mx(r, D), CSx(r, C), CSx(r, D), V2, V7, V8, VD); \ - GS(Mx(r, E), Mx(r, F), CSx(r, E), CSx(r, F), V3, V4, V9, VE); \ - } while (0) - -#endif - -#if SPH_64 - -#define GB(m0, m1, c0, c1, a, b, c, d) do { \ - a = SPH_T64(a + b + (m0 ^ c1)); \ - d = SPH_ROTR64(d ^ a, 32); \ - c = SPH_T64(c + d); \ - b = SPH_ROTR64(b ^ c, 25); \ - a = SPH_T64(a + b + (m1 ^ c0)); \ - d = SPH_ROTR64(d ^ a, 16); \ - c = SPH_T64(c + d); \ - b = SPH_ROTR64(b ^ c, 11); \ - } while (0) - -#if SPH_COMPACT_BLAKE_64 - -#define ROUND_B(r) do { \ - GB(M[sigma[r][0x0]], M[sigma[r][0x1]], \ - CB[sigma[r][0x0]], CB[sigma[r][0x1]], V0, V4, V8, VC); \ - GB(M[sigma[r][0x2]], M[sigma[r][0x3]], \ - CB[sigma[r][0x2]], CB[sigma[r][0x3]], V1, V5, V9, VD); \ - GB(M[sigma[r][0x4]], M[sigma[r][0x5]], \ - CB[sigma[r][0x4]], CB[sigma[r][0x5]], V2, V6, VA, VE); \ - GB(M[sigma[r][0x6]], M[sigma[r][0x7]], \ - CB[sigma[r][0x6]], CB[sigma[r][0x7]], V3, V7, VB, VF); \ - GB(M[sigma[r][0x8]], M[sigma[r][0x9]], \ - CB[sigma[r][0x8]], CB[sigma[r][0x9]], V0, V5, VA, VF); \ - GB(M[sigma[r][0xA]], M[sigma[r][0xB]], \ - CB[sigma[r][0xA]], CB[sigma[r][0xB]], V1, V6, VB, VC); \ - GB(M[sigma[r][0xC]], M[sigma[r][0xD]], \ - CB[sigma[r][0xC]], CB[sigma[r][0xD]], V2, V7, V8, VD); \ - GB(M[sigma[r][0xE]], M[sigma[r][0xF]], \ - CB[sigma[r][0xE]], CB[sigma[r][0xF]], V3, V4, V9, VE); \ - } while (0) - -#else - -#define ROUND_B(r) do { \ - GB(Mx(r, 0), Mx(r, 1), CBx(r, 0), CBx(r, 1), V0, V4, V8, VC); \ - GB(Mx(r, 2), Mx(r, 3), CBx(r, 2), CBx(r, 3), V1, V5, V9, VD); \ - GB(Mx(r, 4), Mx(r, 5), CBx(r, 4), CBx(r, 5), V2, V6, VA, VE); \ - GB(Mx(r, 6), Mx(r, 7), CBx(r, 6), CBx(r, 7), V3, V7, VB, VF); \ - GB(Mx(r, 8), Mx(r, 9), CBx(r, 8), CBx(r, 9), V0, V5, VA, VF); \ - GB(Mx(r, A), Mx(r, B), CBx(r, A), CBx(r, B), V1, V6, VB, VC); \ - GB(Mx(r, C), Mx(r, D), CBx(r, C), CBx(r, D), V2, V7, V8, VD); \ - GB(Mx(r, E), Mx(r, F), CBx(r, E), CBx(r, F), V3, V4, V9, VE); \ - } while (0) - -#endif - -#endif - -#define DECL_STATE32 \ - sph_u32 H0, H1, H2, H3, H4, H5, H6, H7; \ - sph_u32 S0, S1, S2, S3, T0, T1; - -#define READ_STATE32(state) do { \ - H0 = (state)->H[0]; \ - H1 = (state)->H[1]; \ - H2 = (state)->H[2]; \ - H3 = (state)->H[3]; \ - H4 = (state)->H[4]; \ - H5 = (state)->H[5]; \ - H6 = (state)->H[6]; \ - H7 = (state)->H[7]; \ - S0 = (state)->S[0]; \ - S1 = (state)->S[1]; \ - S2 = (state)->S[2]; \ - S3 = (state)->S[3]; \ - T0 = (state)->T0; \ - T1 = (state)->T1; \ - } while (0) - -#define WRITE_STATE32(state) do { \ - (state)->H[0] = H0; \ - (state)->H[1] = H1; \ - (state)->H[2] = H2; \ - (state)->H[3] = H3; \ - (state)->H[4] = H4; \ - (state)->H[5] = H5; \ - (state)->H[6] = H6; \ - (state)->H[7] = H7; \ - (state)->S[0] = S0; \ - (state)->S[1] = S1; \ - (state)->S[2] = S2; \ - (state)->S[3] = S3; \ - (state)->T0 = T0; \ - (state)->T1 = T1; \ - } while (0) - -#if SPH_COMPACT_BLAKE_32 - -#define COMPRESS32 do { \ - sph_u32 M[16]; \ - sph_u32 V0, V1, V2, V3, V4, V5, V6, V7; \ - sph_u32 V8, V9, VA, VB, VC, VD, VE, VF; \ - unsigned r; \ - V0 = H0; \ - V1 = H1; \ - V2 = H2; \ - V3 = H3; \ - V4 = H4; \ - V5 = H5; \ - V6 = H6; \ - V7 = H7; \ - V8 = S0 ^ CS0; \ - V9 = S1 ^ CS1; \ - VA = S2 ^ CS2; \ - VB = S3 ^ CS3; \ - VC = T0 ^ CS4; \ - VD = T0 ^ CS5; \ - VE = T1 ^ CS6; \ - VF = T1 ^ CS7; \ - M[0x0] = sph_dec32be_aligned(buf + 0); \ - M[0x1] = sph_dec32be_aligned(buf + 4); \ - M[0x2] = sph_dec32be_aligned(buf + 8); \ - M[0x3] = sph_dec32be_aligned(buf + 12); \ - M[0x4] = sph_dec32be_aligned(buf + 16); \ - M[0x5] = sph_dec32be_aligned(buf + 20); \ - M[0x6] = sph_dec32be_aligned(buf + 24); \ - M[0x7] = sph_dec32be_aligned(buf + 28); \ - M[0x8] = sph_dec32be_aligned(buf + 32); \ - M[0x9] = sph_dec32be_aligned(buf + 36); \ - M[0xA] = sph_dec32be_aligned(buf + 40); \ - M[0xB] = sph_dec32be_aligned(buf + 44); \ - M[0xC] = sph_dec32be_aligned(buf + 48); \ - M[0xD] = sph_dec32be_aligned(buf + 52); \ - M[0xE] = sph_dec32be_aligned(buf + 56); \ - M[0xF] = sph_dec32be_aligned(buf + 60); \ - for (r = 0; r < 14; r ++) \ - ROUND_S(r); \ - H0 ^= S0 ^ V0 ^ V8; \ - H1 ^= S1 ^ V1 ^ V9; \ - H2 ^= S2 ^ V2 ^ VA; \ - H3 ^= S3 ^ V3 ^ VB; \ - H4 ^= S0 ^ V4 ^ VC; \ - H5 ^= S1 ^ V5 ^ VD; \ - H6 ^= S2 ^ V6 ^ VE; \ - H7 ^= S3 ^ V7 ^ VF; \ - } while (0) - -#else - -#define COMPRESS32 do { \ - sph_u32 M0, M1, M2, M3, M4, M5, M6, M7; \ - sph_u32 M8, M9, MA, MB, MC, MD, ME, MF; \ - sph_u32 V0, V1, V2, V3, V4, V5, V6, V7; \ - sph_u32 V8, V9, VA, VB, VC, VD, VE, VF; \ - V0 = H0; \ - V1 = H1; \ - V2 = H2; \ - V3 = H3; \ - V4 = H4; \ - V5 = H5; \ - V6 = H6; \ - V7 = H7; \ - V8 = S0 ^ CS0; \ - V9 = S1 ^ CS1; \ - VA = S2 ^ CS2; \ - VB = S3 ^ CS3; \ - VC = T0 ^ CS4; \ - VD = T0 ^ CS5; \ - VE = T1 ^ CS6; \ - VF = T1 ^ CS7; \ - M0 = sph_dec32be_aligned(buf + 0); \ - M1 = sph_dec32be_aligned(buf + 4); \ - M2 = sph_dec32be_aligned(buf + 8); \ - M3 = sph_dec32be_aligned(buf + 12); \ - M4 = sph_dec32be_aligned(buf + 16); \ - M5 = sph_dec32be_aligned(buf + 20); \ - M6 = sph_dec32be_aligned(buf + 24); \ - M7 = sph_dec32be_aligned(buf + 28); \ - M8 = sph_dec32be_aligned(buf + 32); \ - M9 = sph_dec32be_aligned(buf + 36); \ - MA = sph_dec32be_aligned(buf + 40); \ - MB = sph_dec32be_aligned(buf + 44); \ - MC = sph_dec32be_aligned(buf + 48); \ - MD = sph_dec32be_aligned(buf + 52); \ - ME = sph_dec32be_aligned(buf + 56); \ - MF = sph_dec32be_aligned(buf + 60); \ - ROUND_S(0); \ - ROUND_S(1); \ - ROUND_S(2); \ - ROUND_S(3); \ - ROUND_S(4); \ - ROUND_S(5); \ - ROUND_S(6); \ - ROUND_S(7); \ - ROUND_S(8); \ - ROUND_S(9); \ - ROUND_S(0); \ - ROUND_S(1); \ - ROUND_S(2); \ - ROUND_S(3); \ - H0 ^= S0 ^ V0 ^ V8; \ - H1 ^= S1 ^ V1 ^ V9; \ - H2 ^= S2 ^ V2 ^ VA; \ - H3 ^= S3 ^ V3 ^ VB; \ - H4 ^= S0 ^ V4 ^ VC; \ - H5 ^= S1 ^ V5 ^ VD; \ - H6 ^= S2 ^ V6 ^ VE; \ - H7 ^= S3 ^ V7 ^ VF; \ - } while (0) - -#endif - -#if SPH_64 - -#define DECL_STATE64 \ - sph_u64 H0, H1, H2, H3, H4, H5, H6, H7; \ - sph_u64 S0, S1, S2, S3, T0, T1; - -#define READ_STATE64(state) do { \ - H0 = (state)->H[0]; \ - H1 = (state)->H[1]; \ - H2 = (state)->H[2]; \ - H3 = (state)->H[3]; \ - H4 = (state)->H[4]; \ - H5 = (state)->H[5]; \ - H6 = (state)->H[6]; \ - H7 = (state)->H[7]; \ - S0 = (state)->S[0]; \ - S1 = (state)->S[1]; \ - S2 = (state)->S[2]; \ - S3 = (state)->S[3]; \ - T0 = (state)->T0; \ - T1 = (state)->T1; \ - } while (0) - -#define WRITE_STATE64(state) do { \ - (state)->H[0] = H0; \ - (state)->H[1] = H1; \ - (state)->H[2] = H2; \ - (state)->H[3] = H3; \ - (state)->H[4] = H4; \ - (state)->H[5] = H5; \ - (state)->H[6] = H6; \ - (state)->H[7] = H7; \ - (state)->S[0] = S0; \ - (state)->S[1] = S1; \ - (state)->S[2] = S2; \ - (state)->S[3] = S3; \ - (state)->T0 = T0; \ - (state)->T1 = T1; \ - } while (0) - -#if SPH_COMPACT_BLAKE_64 - -#define COMPRESS64 do { \ - sph_u64 M[16]; \ - sph_u64 V0, V1, V2, V3, V4, V5, V6, V7; \ - sph_u64 V8, V9, VA, VB, VC, VD, VE, VF; \ - unsigned r; \ - V0 = H0; \ - V1 = H1; \ - V2 = H2; \ - V3 = H3; \ - V4 = H4; \ - V5 = H5; \ - V6 = H6; \ - V7 = H7; \ - V8 = S0 ^ CB0; \ - V9 = S1 ^ CB1; \ - VA = S2 ^ CB2; \ - VB = S3 ^ CB3; \ - VC = T0 ^ CB4; \ - VD = T0 ^ CB5; \ - VE = T1 ^ CB6; \ - VF = T1 ^ CB7; \ - M[0x0] = sph_dec64be_aligned(buf + 0); \ - M[0x1] = sph_dec64be_aligned(buf + 8); \ - M[0x2] = sph_dec64be_aligned(buf + 16); \ - M[0x3] = sph_dec64be_aligned(buf + 24); \ - M[0x4] = sph_dec64be_aligned(buf + 32); \ - M[0x5] = sph_dec64be_aligned(buf + 40); \ - M[0x6] = sph_dec64be_aligned(buf + 48); \ - M[0x7] = sph_dec64be_aligned(buf + 56); \ - M[0x8] = sph_dec64be_aligned(buf + 64); \ - M[0x9] = sph_dec64be_aligned(buf + 72); \ - M[0xA] = sph_dec64be_aligned(buf + 80); \ - M[0xB] = sph_dec64be_aligned(buf + 88); \ - M[0xC] = sph_dec64be_aligned(buf + 96); \ - M[0xD] = sph_dec64be_aligned(buf + 104); \ - M[0xE] = sph_dec64be_aligned(buf + 112); \ - M[0xF] = sph_dec64be_aligned(buf + 120); \ - for (r = 0; r < 16; r ++) \ - ROUND_B(r); \ - H0 ^= S0 ^ V0 ^ V8; \ - H1 ^= S1 ^ V1 ^ V9; \ - H2 ^= S2 ^ V2 ^ VA; \ - H3 ^= S3 ^ V3 ^ VB; \ - H4 ^= S0 ^ V4 ^ VC; \ - H5 ^= S1 ^ V5 ^ VD; \ - H6 ^= S2 ^ V6 ^ VE; \ - H7 ^= S3 ^ V7 ^ VF; \ - } while (0) - -#else - -#define COMPRESS64 do { \ - sph_u64 M0, M1, M2, M3, M4, M5, M6, M7; \ - sph_u64 M8, M9, MA, MB, MC, MD, ME, MF; \ - sph_u64 V0, V1, V2, V3, V4, V5, V6, V7; \ - sph_u64 V8, V9, VA, VB, VC, VD, VE, VF; \ - V0 = H0; \ - V1 = H1; \ - V2 = H2; \ - V3 = H3; \ - V4 = H4; \ - V5 = H5; \ - V6 = H6; \ - V7 = H7; \ - V8 = S0 ^ CB0; \ - V9 = S1 ^ CB1; \ - VA = S2 ^ CB2; \ - VB = S3 ^ CB3; \ - VC = T0 ^ CB4; \ - VD = T0 ^ CB5; \ - VE = T1 ^ CB6; \ - VF = T1 ^ CB7; \ - M0 = sph_dec64be_aligned(buf + 0); \ - M1 = sph_dec64be_aligned(buf + 8); \ - M2 = sph_dec64be_aligned(buf + 16); \ - M3 = sph_dec64be_aligned(buf + 24); \ - M4 = sph_dec64be_aligned(buf + 32); \ - M5 = sph_dec64be_aligned(buf + 40); \ - M6 = sph_dec64be_aligned(buf + 48); \ - M7 = sph_dec64be_aligned(buf + 56); \ - M8 = sph_dec64be_aligned(buf + 64); \ - M9 = sph_dec64be_aligned(buf + 72); \ - MA = sph_dec64be_aligned(buf + 80); \ - MB = sph_dec64be_aligned(buf + 88); \ - MC = sph_dec64be_aligned(buf + 96); \ - MD = sph_dec64be_aligned(buf + 104); \ - ME = sph_dec64be_aligned(buf + 112); \ - MF = sph_dec64be_aligned(buf + 120); \ - ROUND_B(0); \ - ROUND_B(1); \ - ROUND_B(2); \ - ROUND_B(3); \ - ROUND_B(4); \ - ROUND_B(5); \ - ROUND_B(6); \ - ROUND_B(7); \ - ROUND_B(8); \ - ROUND_B(9); \ - ROUND_B(0); \ - ROUND_B(1); \ - ROUND_B(2); \ - ROUND_B(3); \ - ROUND_B(4); \ - ROUND_B(5); \ - H0 ^= S0 ^ V0 ^ V8; \ - H1 ^= S1 ^ V1 ^ V9; \ - H2 ^= S2 ^ V2 ^ VA; \ - H3 ^= S3 ^ V3 ^ VB; \ - H4 ^= S0 ^ V4 ^ VC; \ - H5 ^= S1 ^ V5 ^ VD; \ - H6 ^= S2 ^ V6 ^ VE; \ - H7 ^= S3 ^ V7 ^ VF; \ - } while (0) - -#endif - -#endif - -static const sph_u32 salt_zero_small[4] = { 0, 0, 0, 0 }; - -static void -blake32_init(sph_blake_small_context *sc, - const sph_u32 *iv, const sph_u32 *salt) -{ - memcpy(sc->H, iv, 8 * sizeof(sph_u32)); - memcpy(sc->S, salt, 4 * sizeof(sph_u32)); - sc->T0 = sc->T1 = 0; - sc->ptr = 0; -} - -static void -blake32(sph_blake_small_context *sc, const void *data, size_t len) -{ - unsigned char *buf; - size_t ptr; - DECL_STATE32 - - buf = sc->buf; - ptr = sc->ptr; - if (len < (sizeof sc->buf) - ptr) { - memcpy(buf + ptr, data, len); - ptr += len; - sc->ptr = ptr; - return; - } - - READ_STATE32(sc); - while (len > 0) { - size_t clen; - - clen = (sizeof sc->buf) - ptr; - if (clen > len) - clen = len; - memcpy(buf + ptr, data, clen); - ptr += clen; - data = (const unsigned char *)data + clen; - len -= clen; - if (ptr == sizeof sc->buf) { - if ((T0 = SPH_T32(T0 + 512)) < 512) - T1 = SPH_T32(T1 + 1); - COMPRESS32; - ptr = 0; - } - } - WRITE_STATE32(sc); - sc->ptr = ptr; -} - -static void -blake32_close(sph_blake_small_context *sc, - unsigned ub, unsigned n, void *dst, size_t out_size_w32) -{ - union { - unsigned char buf[64]; - sph_u32 dummy; - } u; - size_t ptr, k; - unsigned bit_len; - unsigned z; - sph_u32 th, tl; - unsigned char *out; - - ptr = sc->ptr; - bit_len = ((unsigned)ptr << 3) + n; - z = 0x80 >> n; - u.buf[ptr] = ((ub & -z) | z) & 0xFF; - tl = sc->T0 + bit_len; - th = sc->T1; - if (ptr == 0 && n == 0) { - sc->T0 = SPH_C32(0xFFFFFE00); - sc->T1 = SPH_C32(0xFFFFFFFF); - } else if (sc->T0 == 0) { - sc->T0 = SPH_C32(0xFFFFFE00) + bit_len; - sc->T1 = SPH_T32(sc->T1 - 1); - } else { - sc->T0 -= 512 - bit_len; - } - if (bit_len <= 446) { - memset(u.buf + ptr + 1, 0, 55 - ptr); - if (out_size_w32 == 8) - u.buf[55] |= 1; - sph_enc32be_aligned(u.buf + 56, th); - sph_enc32be_aligned(u.buf + 60, tl); - blake32(sc, u.buf + ptr, 64 - ptr); - } else { - memset(u.buf + ptr + 1, 0, 63 - ptr); - blake32(sc, u.buf + ptr, 64 - ptr); - sc->T0 = SPH_C32(0xFFFFFE00); - sc->T1 = SPH_C32(0xFFFFFFFF); - memset(u.buf, 0, 56); - if (out_size_w32 == 8) - u.buf[55] = 1; - sph_enc32be_aligned(u.buf + 56, th); - sph_enc32be_aligned(u.buf + 60, tl); - blake32(sc, u.buf, 64); - } - out = dst; - for (k = 0; k < out_size_w32; k ++) - sph_enc32be(out + (k << 2), sc->H[k]); -} - -#if SPH_64 - -static const sph_u64 salt_zero_big[4] = { 0, 0, 0, 0 }; - -static void -blake64_init(sph_blake_big_context *sc, - const sph_u64 *iv, const sph_u64 *salt) -{ - memcpy(sc->H, iv, 8 * sizeof(sph_u64)); - memcpy(sc->S, salt, 4 * sizeof(sph_u64)); - sc->T0 = sc->T1 = 0; - sc->ptr = 0; -} - -static void -blake64(sph_blake_big_context *sc, const void *data, size_t len) -{ - unsigned char *buf; - size_t ptr; - DECL_STATE64 - - buf = sc->buf; - ptr = sc->ptr; - if (len < (sizeof sc->buf) - ptr) { - memcpy(buf + ptr, data, len); - ptr += len; - sc->ptr = ptr; - return; - } - - READ_STATE64(sc); - while (len > 0) { - size_t clen; - - clen = (sizeof sc->buf) - ptr; - if (clen > len) - clen = len; - memcpy(buf + ptr, data, clen); - ptr += clen; - data = (const unsigned char *)data + clen; - len -= clen; - if (ptr == sizeof sc->buf) { - if ((T0 = SPH_T64(T0 + 1024)) < 1024) - T1 = SPH_T64(T1 + 1); - COMPRESS64; - ptr = 0; - } - } - WRITE_STATE64(sc); - sc->ptr = ptr; -} - -static void -blake64_close(sph_blake_big_context *sc, - unsigned ub, unsigned n, void *dst, size_t out_size_w64) -{ - union { - unsigned char buf[128]; - sph_u64 dummy; - } u; - size_t ptr, k; - unsigned bit_len; - unsigned z; - sph_u64 th, tl; - unsigned char *out; - - ptr = sc->ptr; - bit_len = ((unsigned)ptr << 3) + n; - z = 0x80 >> n; - u.buf[ptr] = ((ub & -z) | z) & 0xFF; - tl = sc->T0 + bit_len; - th = sc->T1; - if (ptr == 0 && n == 0) { - sc->T0 = SPH_C64(0xFFFFFFFFFFFFFC00); - sc->T1 = SPH_C64(0xFFFFFFFFFFFFFFFF); - } else if (sc->T0 == 0) { - sc->T0 = SPH_C64(0xFFFFFFFFFFFFFC00) + bit_len; - sc->T1 = SPH_T64(sc->T1 - 1); - } else { - sc->T0 -= 1024 - bit_len; - } - if (bit_len <= 894) { - memset(u.buf + ptr + 1, 0, 111 - ptr); - if (out_size_w64 == 8) - u.buf[111] |= 1; - sph_enc64be_aligned(u.buf + 112, th); - sph_enc64be_aligned(u.buf + 120, tl); - blake64(sc, u.buf + ptr, 128 - ptr); - } else { - memset(u.buf + ptr + 1, 0, 127 - ptr); - blake64(sc, u.buf + ptr, 128 - ptr); - sc->T0 = SPH_C64(0xFFFFFFFFFFFFFC00); - sc->T1 = SPH_C64(0xFFFFFFFFFFFFFFFF); - memset(u.buf, 0, 112); - if (out_size_w64 == 8) - u.buf[111] = 1; - sph_enc64be_aligned(u.buf + 112, th); - sph_enc64be_aligned(u.buf + 120, tl); - blake64(sc, u.buf, 128); - } - out = dst; - for (k = 0; k < out_size_w64; k ++) - sph_enc64be(out + (k << 3), sc->H[k]); -} - -#endif - -/* see sph_blake.h */ -void -sph_blake224_init(void *cc) -{ - blake32_init(cc, IV224, salt_zero_small); -} - -/* see sph_blake.h */ -void -sph_blake224(void *cc, const void *data, size_t len) -{ - blake32(cc, data, len); -} - -/* see sph_blake.h */ -void -sph_blake224_close(void *cc, void *dst) -{ - sph_blake224_addbits_and_close(cc, 0, 0, dst); -} - -/* see sph_blake.h */ -void -sph_blake224_addbits_and_close(void *cc, unsigned ub, unsigned n, void *dst) -{ - blake32_close(cc, ub, n, dst, 7); - sph_blake224_init(cc); -} - -/* see sph_blake.h */ -void -sph_blake256_init(void *cc) -{ - blake32_init(cc, IV256, salt_zero_small); -} - -/* see sph_blake.h */ -void -sph_blake256(void *cc, const void *data, size_t len) -{ - blake32(cc, data, len); -} - -/* see sph_blake.h */ -void -sph_blake256_close(void *cc, void *dst) -{ - sph_blake256_addbits_and_close(cc, 0, 0, dst); -} - -/* see sph_blake.h */ -void -sph_blake256_addbits_and_close(void *cc, unsigned ub, unsigned n, void *dst) -{ - blake32_close(cc, ub, n, dst, 8); - sph_blake256_init(cc); -} - -#if SPH_64 - -/* see sph_blake.h */ -void -sph_blake384_init(void *cc) -{ - blake64_init(cc, IV384, salt_zero_big); -} - -/* see sph_blake.h */ -void -sph_blake384(void *cc, const void *data, size_t len) -{ - blake64(cc, data, len); -} - -/* see sph_blake.h */ -void -sph_blake384_close(void *cc, void *dst) -{ - sph_blake384_addbits_and_close(cc, 0, 0, dst); -} - -/* see sph_blake.h */ -void -sph_blake384_addbits_and_close(void *cc, unsigned ub, unsigned n, void *dst) -{ - blake64_close(cc, ub, n, dst, 6); - sph_blake384_init(cc); -} - -/* see sph_blake.h */ -void -sph_blake512_init(void *cc) -{ - blake64_init(cc, IV512, salt_zero_big); -} - -/* see sph_blake.h */ -void -sph_blake512(void *cc, const void *data, size_t len) -{ - blake64(cc, data, len); -} - -/* see sph_blake.h */ -void -sph_blake512_close(void *cc, void *dst) -{ - sph_blake512_addbits_and_close(cc, 0, 0, dst); -} - -/* see sph_blake.h */ -void -sph_blake512_addbits_and_close(void *cc, unsigned ub, unsigned n, void *dst) -{ - blake64_close(cc, ub, n, dst, 8); - sph_blake512_init(cc); -} - -#endif - -#ifdef __cplusplus -} -#endif diff --git a/src/crypto/bmw.c b/src/crypto/bmw.c deleted file mode 100644 index b89a881e80c8..000000000000 --- a/src/crypto/bmw.c +++ /dev/null @@ -1,965 +0,0 @@ -/* $Id: bmw.c 227 2010-06-16 17:28:38Z tp $ */ -/* - * BMW implementation. - * - * ==========================(LICENSE BEGIN)============================ - * - * Copyright (c) 2007-2010 Projet RNRT SAPHIR - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY - * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, - * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE - * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - * ===========================(LICENSE END)============================= - * - * @author Thomas Pornin - */ - -#include -#include -#include - -#ifdef __cplusplus -extern "C"{ -#endif - -#include "sph_bmw.h" - -#if SPH_SMALL_FOOTPRINT && !defined SPH_SMALL_FOOTPRINT_BMW -#define SPH_SMALL_FOOTPRINT_BMW 1 -#endif - -#ifdef _MSC_VER -#pragma warning (disable: 4146) -#endif - -static const sph_u32 IV224[] = { - SPH_C32(0x00010203), SPH_C32(0x04050607), - SPH_C32(0x08090A0B), SPH_C32(0x0C0D0E0F), - SPH_C32(0x10111213), SPH_C32(0x14151617), - SPH_C32(0x18191A1B), SPH_C32(0x1C1D1E1F), - SPH_C32(0x20212223), SPH_C32(0x24252627), - SPH_C32(0x28292A2B), SPH_C32(0x2C2D2E2F), - SPH_C32(0x30313233), SPH_C32(0x34353637), - SPH_C32(0x38393A3B), SPH_C32(0x3C3D3E3F) -}; - -static const sph_u32 IV256[] = { - SPH_C32(0x40414243), SPH_C32(0x44454647), - SPH_C32(0x48494A4B), SPH_C32(0x4C4D4E4F), - SPH_C32(0x50515253), SPH_C32(0x54555657), - SPH_C32(0x58595A5B), SPH_C32(0x5C5D5E5F), - SPH_C32(0x60616263), SPH_C32(0x64656667), - SPH_C32(0x68696A6B), SPH_C32(0x6C6D6E6F), - SPH_C32(0x70717273), SPH_C32(0x74757677), - SPH_C32(0x78797A7B), SPH_C32(0x7C7D7E7F) -}; - -#if SPH_64 - -static const sph_u64 IV384[] = { - SPH_C64(0x0001020304050607), SPH_C64(0x08090A0B0C0D0E0F), - SPH_C64(0x1011121314151617), SPH_C64(0x18191A1B1C1D1E1F), - SPH_C64(0x2021222324252627), SPH_C64(0x28292A2B2C2D2E2F), - SPH_C64(0x3031323334353637), SPH_C64(0x38393A3B3C3D3E3F), - SPH_C64(0x4041424344454647), SPH_C64(0x48494A4B4C4D4E4F), - SPH_C64(0x5051525354555657), SPH_C64(0x58595A5B5C5D5E5F), - SPH_C64(0x6061626364656667), SPH_C64(0x68696A6B6C6D6E6F), - SPH_C64(0x7071727374757677), SPH_C64(0x78797A7B7C7D7E7F) -}; - -static const sph_u64 IV512[] = { - SPH_C64(0x8081828384858687), SPH_C64(0x88898A8B8C8D8E8F), - SPH_C64(0x9091929394959697), SPH_C64(0x98999A9B9C9D9E9F), - SPH_C64(0xA0A1A2A3A4A5A6A7), SPH_C64(0xA8A9AAABACADAEAF), - SPH_C64(0xB0B1B2B3B4B5B6B7), SPH_C64(0xB8B9BABBBCBDBEBF), - SPH_C64(0xC0C1C2C3C4C5C6C7), SPH_C64(0xC8C9CACBCCCDCECF), - SPH_C64(0xD0D1D2D3D4D5D6D7), SPH_C64(0xD8D9DADBDCDDDEDF), - SPH_C64(0xE0E1E2E3E4E5E6E7), SPH_C64(0xE8E9EAEBECEDEEEF), - SPH_C64(0xF0F1F2F3F4F5F6F7), SPH_C64(0xF8F9FAFBFCFDFEFF) -}; - -#endif - -#define XCAT(x, y) XCAT_(x, y) -#define XCAT_(x, y) x ## y - -#define LPAR ( - -#define I16_16 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 -#define I16_17 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 -#define I16_18 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17 -#define I16_19 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18 -#define I16_20 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19 -#define I16_21 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 -#define I16_22 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21 -#define I16_23 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22 -#define I16_24 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23 -#define I16_25 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24 -#define I16_26 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25 -#define I16_27 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26 -#define I16_28 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27 -#define I16_29 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28 -#define I16_30 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29 -#define I16_31 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30 - -#define M16_16 0, 1, 3, 4, 7, 10, 11 -#define M16_17 1, 2, 4, 5, 8, 11, 12 -#define M16_18 2, 3, 5, 6, 9, 12, 13 -#define M16_19 3, 4, 6, 7, 10, 13, 14 -#define M16_20 4, 5, 7, 8, 11, 14, 15 -#define M16_21 5, 6, 8, 9, 12, 15, 16 -#define M16_22 6, 7, 9, 10, 13, 0, 1 -#define M16_23 7, 8, 10, 11, 14, 1, 2 -#define M16_24 8, 9, 11, 12, 15, 2, 3 -#define M16_25 9, 10, 12, 13, 0, 3, 4 -#define M16_26 10, 11, 13, 14, 1, 4, 5 -#define M16_27 11, 12, 14, 15, 2, 5, 6 -#define M16_28 12, 13, 15, 16, 3, 6, 7 -#define M16_29 13, 14, 0, 1, 4, 7, 8 -#define M16_30 14, 15, 1, 2, 5, 8, 9 -#define M16_31 15, 16, 2, 3, 6, 9, 10 - -#define ss0(x) (((x) >> 1) ^ SPH_T32((x) << 3) \ - ^ SPH_ROTL32(x, 4) ^ SPH_ROTL32(x, 19)) -#define ss1(x) (((x) >> 1) ^ SPH_T32((x) << 2) \ - ^ SPH_ROTL32(x, 8) ^ SPH_ROTL32(x, 23)) -#define ss2(x) (((x) >> 2) ^ SPH_T32((x) << 1) \ - ^ SPH_ROTL32(x, 12) ^ SPH_ROTL32(x, 25)) -#define ss3(x) (((x) >> 2) ^ SPH_T32((x) << 2) \ - ^ SPH_ROTL32(x, 15) ^ SPH_ROTL32(x, 29)) -#define ss4(x) (((x) >> 1) ^ (x)) -#define ss5(x) (((x) >> 2) ^ (x)) -#define rs1(x) SPH_ROTL32(x, 3) -#define rs2(x) SPH_ROTL32(x, 7) -#define rs3(x) SPH_ROTL32(x, 13) -#define rs4(x) SPH_ROTL32(x, 16) -#define rs5(x) SPH_ROTL32(x, 19) -#define rs6(x) SPH_ROTL32(x, 23) -#define rs7(x) SPH_ROTL32(x, 27) - -#define Ks(j) SPH_T32((sph_u32)(j) * SPH_C32(0x05555555)) - -#define add_elt_s(mf, hf, j0m, j1m, j3m, j4m, j7m, j10m, j11m, j16) \ - (SPH_T32(SPH_ROTL32(mf(j0m), j1m) + SPH_ROTL32(mf(j3m), j4m) \ - - SPH_ROTL32(mf(j10m), j11m) + Ks(j16)) ^ hf(j7m)) - -#define expand1s_inner(qf, mf, hf, i16, \ - i0, i1, i2, i3, i4, i5, i6, i7, i8, \ - i9, i10, i11, i12, i13, i14, i15, \ - i0m, i1m, i3m, i4m, i7m, i10m, i11m) \ - SPH_T32(ss1(qf(i0)) + ss2(qf(i1)) + ss3(qf(i2)) + ss0(qf(i3)) \ - + ss1(qf(i4)) + ss2(qf(i5)) + ss3(qf(i6)) + ss0(qf(i7)) \ - + ss1(qf(i8)) + ss2(qf(i9)) + ss3(qf(i10)) + ss0(qf(i11)) \ - + ss1(qf(i12)) + ss2(qf(i13)) + ss3(qf(i14)) + ss0(qf(i15)) \ - + add_elt_s(mf, hf, i0m, i1m, i3m, i4m, i7m, i10m, i11m, i16)) - -#define expand1s(qf, mf, hf, i16) \ - expand1s_(qf, mf, hf, i16, I16_ ## i16, M16_ ## i16) -#define expand1s_(qf, mf, hf, i16, ix, iy) \ - expand1s_inner LPAR qf, mf, hf, i16, ix, iy) - -#define expand2s_inner(qf, mf, hf, i16, \ - i0, i1, i2, i3, i4, i5, i6, i7, i8, \ - i9, i10, i11, i12, i13, i14, i15, \ - i0m, i1m, i3m, i4m, i7m, i10m, i11m) \ - SPH_T32(qf(i0) + rs1(qf(i1)) + qf(i2) + rs2(qf(i3)) \ - + qf(i4) + rs3(qf(i5)) + qf(i6) + rs4(qf(i7)) \ - + qf(i8) + rs5(qf(i9)) + qf(i10) + rs6(qf(i11)) \ - + qf(i12) + rs7(qf(i13)) + ss4(qf(i14)) + ss5(qf(i15)) \ - + add_elt_s(mf, hf, i0m, i1m, i3m, i4m, i7m, i10m, i11m, i16)) - -#define expand2s(qf, mf, hf, i16) \ - expand2s_(qf, mf, hf, i16, I16_ ## i16, M16_ ## i16) -#define expand2s_(qf, mf, hf, i16, ix, iy) \ - expand2s_inner LPAR qf, mf, hf, i16, ix, iy) - -#if SPH_64 - -#define sb0(x) (((x) >> 1) ^ SPH_T64((x) << 3) \ - ^ SPH_ROTL64(x, 4) ^ SPH_ROTL64(x, 37)) -#define sb1(x) (((x) >> 1) ^ SPH_T64((x) << 2) \ - ^ SPH_ROTL64(x, 13) ^ SPH_ROTL64(x, 43)) -#define sb2(x) (((x) >> 2) ^ SPH_T64((x) << 1) \ - ^ SPH_ROTL64(x, 19) ^ SPH_ROTL64(x, 53)) -#define sb3(x) (((x) >> 2) ^ SPH_T64((x) << 2) \ - ^ SPH_ROTL64(x, 28) ^ SPH_ROTL64(x, 59)) -#define sb4(x) (((x) >> 1) ^ (x)) -#define sb5(x) (((x) >> 2) ^ (x)) -#define rb1(x) SPH_ROTL64(x, 5) -#define rb2(x) SPH_ROTL64(x, 11) -#define rb3(x) SPH_ROTL64(x, 27) -#define rb4(x) SPH_ROTL64(x, 32) -#define rb5(x) SPH_ROTL64(x, 37) -#define rb6(x) SPH_ROTL64(x, 43) -#define rb7(x) SPH_ROTL64(x, 53) - -#define Kb(j) SPH_T64((sph_u64)(j) * SPH_C64(0x0555555555555555)) - -#if SPH_SMALL_FOOTPRINT_BMW - -static const sph_u64 Kb_tab[] = { - Kb(16), Kb(17), Kb(18), Kb(19), Kb(20), Kb(21), Kb(22), Kb(23), - Kb(24), Kb(25), Kb(26), Kb(27), Kb(28), Kb(29), Kb(30), Kb(31) -}; - -#define rol_off(mf, j, off) \ - SPH_ROTL64(mf(((j) + (off)) & 15), (((j) + (off)) & 15) + 1) - -#define add_elt_b(mf, hf, j) \ - (SPH_T64(rol_off(mf, j, 0) + rol_off(mf, j, 3) \ - - rol_off(mf, j, 10) + Kb_tab[j]) ^ hf(((j) + 7) & 15)) - -#define expand1b(qf, mf, hf, i) \ - SPH_T64(sb1(qf((i) - 16)) + sb2(qf((i) - 15)) \ - + sb3(qf((i) - 14)) + sb0(qf((i) - 13)) \ - + sb1(qf((i) - 12)) + sb2(qf((i) - 11)) \ - + sb3(qf((i) - 10)) + sb0(qf((i) - 9)) \ - + sb1(qf((i) - 8)) + sb2(qf((i) - 7)) \ - + sb3(qf((i) - 6)) + sb0(qf((i) - 5)) \ - + sb1(qf((i) - 4)) + sb2(qf((i) - 3)) \ - + sb3(qf((i) - 2)) + sb0(qf((i) - 1)) \ - + add_elt_b(mf, hf, (i) - 16)) - -#define expand2b(qf, mf, hf, i) \ - SPH_T64(qf((i) - 16) + rb1(qf((i) - 15)) \ - + qf((i) - 14) + rb2(qf((i) - 13)) \ - + qf((i) - 12) + rb3(qf((i) - 11)) \ - + qf((i) - 10) + rb4(qf((i) - 9)) \ - + qf((i) - 8) + rb5(qf((i) - 7)) \ - + qf((i) - 6) + rb6(qf((i) - 5)) \ - + qf((i) - 4) + rb7(qf((i) - 3)) \ - + sb4(qf((i) - 2)) + sb5(qf((i) - 1)) \ - + add_elt_b(mf, hf, (i) - 16)) - -#else - -#define add_elt_b(mf, hf, j0m, j1m, j3m, j4m, j7m, j10m, j11m, j16) \ - (SPH_T64(SPH_ROTL64(mf(j0m), j1m) + SPH_ROTL64(mf(j3m), j4m) \ - - SPH_ROTL64(mf(j10m), j11m) + Kb(j16)) ^ hf(j7m)) - -#define expand1b_inner(qf, mf, hf, i16, \ - i0, i1, i2, i3, i4, i5, i6, i7, i8, \ - i9, i10, i11, i12, i13, i14, i15, \ - i0m, i1m, i3m, i4m, i7m, i10m, i11m) \ - SPH_T64(sb1(qf(i0)) + sb2(qf(i1)) + sb3(qf(i2)) + sb0(qf(i3)) \ - + sb1(qf(i4)) + sb2(qf(i5)) + sb3(qf(i6)) + sb0(qf(i7)) \ - + sb1(qf(i8)) + sb2(qf(i9)) + sb3(qf(i10)) + sb0(qf(i11)) \ - + sb1(qf(i12)) + sb2(qf(i13)) + sb3(qf(i14)) + sb0(qf(i15)) \ - + add_elt_b(mf, hf, i0m, i1m, i3m, i4m, i7m, i10m, i11m, i16)) - -#define expand1b(qf, mf, hf, i16) \ - expand1b_(qf, mf, hf, i16, I16_ ## i16, M16_ ## i16) -#define expand1b_(qf, mf, hf, i16, ix, iy) \ - expand1b_inner LPAR qf, mf, hf, i16, ix, iy) - -#define expand2b_inner(qf, mf, hf, i16, \ - i0, i1, i2, i3, i4, i5, i6, i7, i8, \ - i9, i10, i11, i12, i13, i14, i15, \ - i0m, i1m, i3m, i4m, i7m, i10m, i11m) \ - SPH_T64(qf(i0) + rb1(qf(i1)) + qf(i2) + rb2(qf(i3)) \ - + qf(i4) + rb3(qf(i5)) + qf(i6) + rb4(qf(i7)) \ - + qf(i8) + rb5(qf(i9)) + qf(i10) + rb6(qf(i11)) \ - + qf(i12) + rb7(qf(i13)) + sb4(qf(i14)) + sb5(qf(i15)) \ - + add_elt_b(mf, hf, i0m, i1m, i3m, i4m, i7m, i10m, i11m, i16)) - -#define expand2b(qf, mf, hf, i16) \ - expand2b_(qf, mf, hf, i16, I16_ ## i16, M16_ ## i16) -#define expand2b_(qf, mf, hf, i16, ix, iy) \ - expand2b_inner LPAR qf, mf, hf, i16, ix, iy) - -#endif - -#endif - -#define MAKE_W(tt, i0, op01, i1, op12, i2, op23, i3, op34, i4) \ - tt((M(i0) ^ H(i0)) op01 (M(i1) ^ H(i1)) op12 (M(i2) ^ H(i2)) \ - op23 (M(i3) ^ H(i3)) op34 (M(i4) ^ H(i4))) - -#define Ws0 MAKE_W(SPH_T32, 5, -, 7, +, 10, +, 13, +, 14) -#define Ws1 MAKE_W(SPH_T32, 6, -, 8, +, 11, +, 14, -, 15) -#define Ws2 MAKE_W(SPH_T32, 0, +, 7, +, 9, -, 12, +, 15) -#define Ws3 MAKE_W(SPH_T32, 0, -, 1, +, 8, -, 10, +, 13) -#define Ws4 MAKE_W(SPH_T32, 1, +, 2, +, 9, -, 11, -, 14) -#define Ws5 MAKE_W(SPH_T32, 3, -, 2, +, 10, -, 12, +, 15) -#define Ws6 MAKE_W(SPH_T32, 4, -, 0, -, 3, -, 11, +, 13) -#define Ws7 MAKE_W(SPH_T32, 1, -, 4, -, 5, -, 12, -, 14) -#define Ws8 MAKE_W(SPH_T32, 2, -, 5, -, 6, +, 13, -, 15) -#define Ws9 MAKE_W(SPH_T32, 0, -, 3, +, 6, -, 7, +, 14) -#define Ws10 MAKE_W(SPH_T32, 8, -, 1, -, 4, -, 7, +, 15) -#define Ws11 MAKE_W(SPH_T32, 8, -, 0, -, 2, -, 5, +, 9) -#define Ws12 MAKE_W(SPH_T32, 1, +, 3, -, 6, -, 9, +, 10) -#define Ws13 MAKE_W(SPH_T32, 2, +, 4, +, 7, +, 10, +, 11) -#define Ws14 MAKE_W(SPH_T32, 3, -, 5, +, 8, -, 11, -, 12) -#define Ws15 MAKE_W(SPH_T32, 12, -, 4, -, 6, -, 9, +, 13) - -#if SPH_SMALL_FOOTPRINT_BMW - -#define MAKE_Qas do { \ - unsigned u; \ - sph_u32 Ws[16]; \ - Ws[ 0] = Ws0; \ - Ws[ 1] = Ws1; \ - Ws[ 2] = Ws2; \ - Ws[ 3] = Ws3; \ - Ws[ 4] = Ws4; \ - Ws[ 5] = Ws5; \ - Ws[ 6] = Ws6; \ - Ws[ 7] = Ws7; \ - Ws[ 8] = Ws8; \ - Ws[ 9] = Ws9; \ - Ws[10] = Ws10; \ - Ws[11] = Ws11; \ - Ws[12] = Ws12; \ - Ws[13] = Ws13; \ - Ws[14] = Ws14; \ - Ws[15] = Ws15; \ - for (u = 0; u < 15; u += 5) { \ - qt[u + 0] = SPH_T32(ss0(Ws[u + 0]) + H(u + 1)); \ - qt[u + 1] = SPH_T32(ss1(Ws[u + 1]) + H(u + 2)); \ - qt[u + 2] = SPH_T32(ss2(Ws[u + 2]) + H(u + 3)); \ - qt[u + 3] = SPH_T32(ss3(Ws[u + 3]) + H(u + 4)); \ - qt[u + 4] = SPH_T32(ss4(Ws[u + 4]) + H(u + 5)); \ - } \ - qt[15] = SPH_T32(ss0(Ws[15]) + H(0)); \ - } while (0) - -#define MAKE_Qbs do { \ - qt[16] = expand1s(Qs, M, H, 16); \ - qt[17] = expand1s(Qs, M, H, 17); \ - qt[18] = expand2s(Qs, M, H, 18); \ - qt[19] = expand2s(Qs, M, H, 19); \ - qt[20] = expand2s(Qs, M, H, 20); \ - qt[21] = expand2s(Qs, M, H, 21); \ - qt[22] = expand2s(Qs, M, H, 22); \ - qt[23] = expand2s(Qs, M, H, 23); \ - qt[24] = expand2s(Qs, M, H, 24); \ - qt[25] = expand2s(Qs, M, H, 25); \ - qt[26] = expand2s(Qs, M, H, 26); \ - qt[27] = expand2s(Qs, M, H, 27); \ - qt[28] = expand2s(Qs, M, H, 28); \ - qt[29] = expand2s(Qs, M, H, 29); \ - qt[30] = expand2s(Qs, M, H, 30); \ - qt[31] = expand2s(Qs, M, H, 31); \ - } while (0) - -#else - -#define MAKE_Qas do { \ - qt[ 0] = SPH_T32(ss0(Ws0 ) + H( 1)); \ - qt[ 1] = SPH_T32(ss1(Ws1 ) + H( 2)); \ - qt[ 2] = SPH_T32(ss2(Ws2 ) + H( 3)); \ - qt[ 3] = SPH_T32(ss3(Ws3 ) + H( 4)); \ - qt[ 4] = SPH_T32(ss4(Ws4 ) + H( 5)); \ - qt[ 5] = SPH_T32(ss0(Ws5 ) + H( 6)); \ - qt[ 6] = SPH_T32(ss1(Ws6 ) + H( 7)); \ - qt[ 7] = SPH_T32(ss2(Ws7 ) + H( 8)); \ - qt[ 8] = SPH_T32(ss3(Ws8 ) + H( 9)); \ - qt[ 9] = SPH_T32(ss4(Ws9 ) + H(10)); \ - qt[10] = SPH_T32(ss0(Ws10) + H(11)); \ - qt[11] = SPH_T32(ss1(Ws11) + H(12)); \ - qt[12] = SPH_T32(ss2(Ws12) + H(13)); \ - qt[13] = SPH_T32(ss3(Ws13) + H(14)); \ - qt[14] = SPH_T32(ss4(Ws14) + H(15)); \ - qt[15] = SPH_T32(ss0(Ws15) + H( 0)); \ - } while (0) - -#define MAKE_Qbs do { \ - qt[16] = expand1s(Qs, M, H, 16); \ - qt[17] = expand1s(Qs, M, H, 17); \ - qt[18] = expand2s(Qs, M, H, 18); \ - qt[19] = expand2s(Qs, M, H, 19); \ - qt[20] = expand2s(Qs, M, H, 20); \ - qt[21] = expand2s(Qs, M, H, 21); \ - qt[22] = expand2s(Qs, M, H, 22); \ - qt[23] = expand2s(Qs, M, H, 23); \ - qt[24] = expand2s(Qs, M, H, 24); \ - qt[25] = expand2s(Qs, M, H, 25); \ - qt[26] = expand2s(Qs, M, H, 26); \ - qt[27] = expand2s(Qs, M, H, 27); \ - qt[28] = expand2s(Qs, M, H, 28); \ - qt[29] = expand2s(Qs, M, H, 29); \ - qt[30] = expand2s(Qs, M, H, 30); \ - qt[31] = expand2s(Qs, M, H, 31); \ - } while (0) - -#endif - -#define MAKE_Qs do { \ - MAKE_Qas; \ - MAKE_Qbs; \ - } while (0) - -#define Qs(j) (qt[j]) - -#if SPH_64 - -#define Wb0 MAKE_W(SPH_T64, 5, -, 7, +, 10, +, 13, +, 14) -#define Wb1 MAKE_W(SPH_T64, 6, -, 8, +, 11, +, 14, -, 15) -#define Wb2 MAKE_W(SPH_T64, 0, +, 7, +, 9, -, 12, +, 15) -#define Wb3 MAKE_W(SPH_T64, 0, -, 1, +, 8, -, 10, +, 13) -#define Wb4 MAKE_W(SPH_T64, 1, +, 2, +, 9, -, 11, -, 14) -#define Wb5 MAKE_W(SPH_T64, 3, -, 2, +, 10, -, 12, +, 15) -#define Wb6 MAKE_W(SPH_T64, 4, -, 0, -, 3, -, 11, +, 13) -#define Wb7 MAKE_W(SPH_T64, 1, -, 4, -, 5, -, 12, -, 14) -#define Wb8 MAKE_W(SPH_T64, 2, -, 5, -, 6, +, 13, -, 15) -#define Wb9 MAKE_W(SPH_T64, 0, -, 3, +, 6, -, 7, +, 14) -#define Wb10 MAKE_W(SPH_T64, 8, -, 1, -, 4, -, 7, +, 15) -#define Wb11 MAKE_W(SPH_T64, 8, -, 0, -, 2, -, 5, +, 9) -#define Wb12 MAKE_W(SPH_T64, 1, +, 3, -, 6, -, 9, +, 10) -#define Wb13 MAKE_W(SPH_T64, 2, +, 4, +, 7, +, 10, +, 11) -#define Wb14 MAKE_W(SPH_T64, 3, -, 5, +, 8, -, 11, -, 12) -#define Wb15 MAKE_W(SPH_T64, 12, -, 4, -, 6, -, 9, +, 13) - -#if SPH_SMALL_FOOTPRINT_BMW - -#define MAKE_Qab do { \ - unsigned u; \ - sph_u64 Wb[16]; \ - Wb[ 0] = Wb0; \ - Wb[ 1] = Wb1; \ - Wb[ 2] = Wb2; \ - Wb[ 3] = Wb3; \ - Wb[ 4] = Wb4; \ - Wb[ 5] = Wb5; \ - Wb[ 6] = Wb6; \ - Wb[ 7] = Wb7; \ - Wb[ 8] = Wb8; \ - Wb[ 9] = Wb9; \ - Wb[10] = Wb10; \ - Wb[11] = Wb11; \ - Wb[12] = Wb12; \ - Wb[13] = Wb13; \ - Wb[14] = Wb14; \ - Wb[15] = Wb15; \ - for (u = 0; u < 15; u += 5) { \ - qt[u + 0] = SPH_T64(sb0(Wb[u + 0]) + H(u + 1)); \ - qt[u + 1] = SPH_T64(sb1(Wb[u + 1]) + H(u + 2)); \ - qt[u + 2] = SPH_T64(sb2(Wb[u + 2]) + H(u + 3)); \ - qt[u + 3] = SPH_T64(sb3(Wb[u + 3]) + H(u + 4)); \ - qt[u + 4] = SPH_T64(sb4(Wb[u + 4]) + H(u + 5)); \ - } \ - qt[15] = SPH_T64(sb0(Wb[15]) + H(0)); \ - } while (0) - -#define MAKE_Qbb do { \ - unsigned u; \ - for (u = 16; u < 18; u ++) \ - qt[u] = expand1b(Qb, M, H, u); \ - for (u = 18; u < 32; u ++) \ - qt[u] = expand2b(Qb, M, H, u); \ - } while (0) - -#else - -#define MAKE_Qab do { \ - qt[ 0] = SPH_T64(sb0(Wb0 ) + H( 1)); \ - qt[ 1] = SPH_T64(sb1(Wb1 ) + H( 2)); \ - qt[ 2] = SPH_T64(sb2(Wb2 ) + H( 3)); \ - qt[ 3] = SPH_T64(sb3(Wb3 ) + H( 4)); \ - qt[ 4] = SPH_T64(sb4(Wb4 ) + H( 5)); \ - qt[ 5] = SPH_T64(sb0(Wb5 ) + H( 6)); \ - qt[ 6] = SPH_T64(sb1(Wb6 ) + H( 7)); \ - qt[ 7] = SPH_T64(sb2(Wb7 ) + H( 8)); \ - qt[ 8] = SPH_T64(sb3(Wb8 ) + H( 9)); \ - qt[ 9] = SPH_T64(sb4(Wb9 ) + H(10)); \ - qt[10] = SPH_T64(sb0(Wb10) + H(11)); \ - qt[11] = SPH_T64(sb1(Wb11) + H(12)); \ - qt[12] = SPH_T64(sb2(Wb12) + H(13)); \ - qt[13] = SPH_T64(sb3(Wb13) + H(14)); \ - qt[14] = SPH_T64(sb4(Wb14) + H(15)); \ - qt[15] = SPH_T64(sb0(Wb15) + H( 0)); \ - } while (0) - -#define MAKE_Qbb do { \ - qt[16] = expand1b(Qb, M, H, 16); \ - qt[17] = expand1b(Qb, M, H, 17); \ - qt[18] = expand2b(Qb, M, H, 18); \ - qt[19] = expand2b(Qb, M, H, 19); \ - qt[20] = expand2b(Qb, M, H, 20); \ - qt[21] = expand2b(Qb, M, H, 21); \ - qt[22] = expand2b(Qb, M, H, 22); \ - qt[23] = expand2b(Qb, M, H, 23); \ - qt[24] = expand2b(Qb, M, H, 24); \ - qt[25] = expand2b(Qb, M, H, 25); \ - qt[26] = expand2b(Qb, M, H, 26); \ - qt[27] = expand2b(Qb, M, H, 27); \ - qt[28] = expand2b(Qb, M, H, 28); \ - qt[29] = expand2b(Qb, M, H, 29); \ - qt[30] = expand2b(Qb, M, H, 30); \ - qt[31] = expand2b(Qb, M, H, 31); \ - } while (0) - -#endif - -#define MAKE_Qb do { \ - MAKE_Qab; \ - MAKE_Qbb; \ - } while (0) - -#define Qb(j) (qt[j]) - -#endif - -#define FOLD(type, mkQ, tt, rol, mf, qf, dhf) do { \ - type qt[32], xl, xh; \ - mkQ; \ - xl = qf(16) ^ qf(17) ^ qf(18) ^ qf(19) \ - ^ qf(20) ^ qf(21) ^ qf(22) ^ qf(23); \ - xh = xl ^ qf(24) ^ qf(25) ^ qf(26) ^ qf(27) \ - ^ qf(28) ^ qf(29) ^ qf(30) ^ qf(31); \ - dhf( 0) = tt(((xh << 5) ^ (qf(16) >> 5) ^ mf( 0)) \ - + (xl ^ qf(24) ^ qf( 0))); \ - dhf( 1) = tt(((xh >> 7) ^ (qf(17) << 8) ^ mf( 1)) \ - + (xl ^ qf(25) ^ qf( 1))); \ - dhf( 2) = tt(((xh >> 5) ^ (qf(18) << 5) ^ mf( 2)) \ - + (xl ^ qf(26) ^ qf( 2))); \ - dhf( 3) = tt(((xh >> 1) ^ (qf(19) << 5) ^ mf( 3)) \ - + (xl ^ qf(27) ^ qf( 3))); \ - dhf( 4) = tt(((xh >> 3) ^ (qf(20) << 0) ^ mf( 4)) \ - + (xl ^ qf(28) ^ qf( 4))); \ - dhf( 5) = tt(((xh << 6) ^ (qf(21) >> 6) ^ mf( 5)) \ - + (xl ^ qf(29) ^ qf( 5))); \ - dhf( 6) = tt(((xh >> 4) ^ (qf(22) << 6) ^ mf( 6)) \ - + (xl ^ qf(30) ^ qf( 6))); \ - dhf( 7) = tt(((xh >> 11) ^ (qf(23) << 2) ^ mf( 7)) \ - + (xl ^ qf(31) ^ qf( 7))); \ - dhf( 8) = tt(rol(dhf(4), 9) + (xh ^ qf(24) ^ mf( 8)) \ - + ((xl << 8) ^ qf(23) ^ qf( 8))); \ - dhf( 9) = tt(rol(dhf(5), 10) + (xh ^ qf(25) ^ mf( 9)) \ - + ((xl >> 6) ^ qf(16) ^ qf( 9))); \ - dhf(10) = tt(rol(dhf(6), 11) + (xh ^ qf(26) ^ mf(10)) \ - + ((xl << 6) ^ qf(17) ^ qf(10))); \ - dhf(11) = tt(rol(dhf(7), 12) + (xh ^ qf(27) ^ mf(11)) \ - + ((xl << 4) ^ qf(18) ^ qf(11))); \ - dhf(12) = tt(rol(dhf(0), 13) + (xh ^ qf(28) ^ mf(12)) \ - + ((xl >> 3) ^ qf(19) ^ qf(12))); \ - dhf(13) = tt(rol(dhf(1), 14) + (xh ^ qf(29) ^ mf(13)) \ - + ((xl >> 4) ^ qf(20) ^ qf(13))); \ - dhf(14) = tt(rol(dhf(2), 15) + (xh ^ qf(30) ^ mf(14)) \ - + ((xl >> 7) ^ qf(21) ^ qf(14))); \ - dhf(15) = tt(rol(dhf(3), 16) + (xh ^ qf(31) ^ mf(15)) \ - + ((xl >> 2) ^ qf(22) ^ qf(15))); \ - } while (0) - -#define FOLDs FOLD(sph_u32, MAKE_Qs, SPH_T32, SPH_ROTL32, M, Qs, dH) - -#if SPH_64 - -#define FOLDb FOLD(sph_u64, MAKE_Qb, SPH_T64, SPH_ROTL64, M, Qb, dH) - -#endif - -static void -compress_small(const unsigned char *data, const sph_u32 h[16], sph_u32 dh[16]) -{ -#if SPH_LITTLE_FAST -#define M(x) sph_dec32le_aligned(data + 4 * (x)) -#else - sph_u32 mv[16]; - - mv[ 0] = sph_dec32le_aligned(data + 0); - mv[ 1] = sph_dec32le_aligned(data + 4); - mv[ 2] = sph_dec32le_aligned(data + 8); - mv[ 3] = sph_dec32le_aligned(data + 12); - mv[ 4] = sph_dec32le_aligned(data + 16); - mv[ 5] = sph_dec32le_aligned(data + 20); - mv[ 6] = sph_dec32le_aligned(data + 24); - mv[ 7] = sph_dec32le_aligned(data + 28); - mv[ 8] = sph_dec32le_aligned(data + 32); - mv[ 9] = sph_dec32le_aligned(data + 36); - mv[10] = sph_dec32le_aligned(data + 40); - mv[11] = sph_dec32le_aligned(data + 44); - mv[12] = sph_dec32le_aligned(data + 48); - mv[13] = sph_dec32le_aligned(data + 52); - mv[14] = sph_dec32le_aligned(data + 56); - mv[15] = sph_dec32le_aligned(data + 60); -#define M(x) (mv[x]) -#endif -#define H(x) (h[x]) -#define dH(x) (dh[x]) - - FOLDs; - -#undef M -#undef H -#undef dH -} - -static const sph_u32 final_s[16] = { - SPH_C32(0xaaaaaaa0), SPH_C32(0xaaaaaaa1), SPH_C32(0xaaaaaaa2), - SPH_C32(0xaaaaaaa3), SPH_C32(0xaaaaaaa4), SPH_C32(0xaaaaaaa5), - SPH_C32(0xaaaaaaa6), SPH_C32(0xaaaaaaa7), SPH_C32(0xaaaaaaa8), - SPH_C32(0xaaaaaaa9), SPH_C32(0xaaaaaaaa), SPH_C32(0xaaaaaaab), - SPH_C32(0xaaaaaaac), SPH_C32(0xaaaaaaad), SPH_C32(0xaaaaaaae), - SPH_C32(0xaaaaaaaf) -}; - -static void -bmw32_init(sph_bmw_small_context *sc, const sph_u32 *iv) -{ - memcpy(sc->H, iv, sizeof sc->H); - sc->ptr = 0; -#if SPH_64 - sc->bit_count = 0; -#else - sc->bit_count_high = 0; - sc->bit_count_low = 0; -#endif -} - -static void -bmw32(sph_bmw_small_context *sc, const void *data, size_t len) -{ - unsigned char *buf; - size_t ptr; - sph_u32 htmp[16]; - sph_u32 *h1, *h2; -#if !SPH_64 - sph_u32 tmp; -#endif - -#if SPH_64 - sc->bit_count += (sph_u64)len << 3; -#else - tmp = sc->bit_count_low; - sc->bit_count_low = SPH_T32(tmp + ((sph_u32)len << 3)); - if (sc->bit_count_low < tmp) - sc->bit_count_high ++; - sc->bit_count_high += len >> 29; -#endif - buf = sc->buf; - ptr = sc->ptr; - h1 = sc->H; - h2 = htmp; - while (len > 0) { - size_t clen; - - clen = (sizeof sc->buf) - ptr; - if (clen > len) - clen = len; - memcpy(buf + ptr, data, clen); - data = (const unsigned char *)data + clen; - len -= clen; - ptr += clen; - if (ptr == sizeof sc->buf) { - sph_u32 *ht; - - compress_small(buf, h1, h2); - ht = h1; - h1 = h2; - h2 = ht; - ptr = 0; - } - } - sc->ptr = ptr; - if (h1 != sc->H) - memcpy(sc->H, h1, sizeof sc->H); -} - -static void -bmw32_close(sph_bmw_small_context *sc, unsigned ub, unsigned n, - void *dst, size_t out_size_w32) -{ - unsigned char *buf, *out; - size_t ptr, u, v; - unsigned z; - sph_u32 h1[16], h2[16], *h; - - buf = sc->buf; - ptr = sc->ptr; - z = 0x80 >> n; - buf[ptr ++] = ((ub & -z) | z) & 0xFF; - h = sc->H; - if (ptr > (sizeof sc->buf) - 8) { - memset(buf + ptr, 0, (sizeof sc->buf) - ptr); - compress_small(buf, h, h1); - ptr = 0; - h = h1; - } - memset(buf + ptr, 0, (sizeof sc->buf) - 8 - ptr); -#if SPH_64 - sph_enc64le_aligned(buf + (sizeof sc->buf) - 8, - SPH_T64(sc->bit_count + n)); -#else - sph_enc32le_aligned(buf + (sizeof sc->buf) - 8, - sc->bit_count_low + n); - sph_enc32le_aligned(buf + (sizeof sc->buf) - 4, - SPH_T32(sc->bit_count_high)); -#endif - compress_small(buf, h, h2); - for (u = 0; u < 16; u ++) - sph_enc32le_aligned(buf + 4 * u, h2[u]); - compress_small(buf, final_s, h1); - out = dst; - for (u = 0, v = 16 - out_size_w32; u < out_size_w32; u ++, v ++) - sph_enc32le(out + 4 * u, h1[v]); -} - -#if SPH_64 - -static void -compress_big(const unsigned char *data, const sph_u64 h[16], sph_u64 dh[16]) -{ -#if SPH_LITTLE_FAST -#define M(x) sph_dec64le_aligned(data + 8 * (x)) -#else - sph_u64 mv[16]; - - mv[ 0] = sph_dec64le_aligned(data + 0); - mv[ 1] = sph_dec64le_aligned(data + 8); - mv[ 2] = sph_dec64le_aligned(data + 16); - mv[ 3] = sph_dec64le_aligned(data + 24); - mv[ 4] = sph_dec64le_aligned(data + 32); - mv[ 5] = sph_dec64le_aligned(data + 40); - mv[ 6] = sph_dec64le_aligned(data + 48); - mv[ 7] = sph_dec64le_aligned(data + 56); - mv[ 8] = sph_dec64le_aligned(data + 64); - mv[ 9] = sph_dec64le_aligned(data + 72); - mv[10] = sph_dec64le_aligned(data + 80); - mv[11] = sph_dec64le_aligned(data + 88); - mv[12] = sph_dec64le_aligned(data + 96); - mv[13] = sph_dec64le_aligned(data + 104); - mv[14] = sph_dec64le_aligned(data + 112); - mv[15] = sph_dec64le_aligned(data + 120); -#define M(x) (mv[x]) -#endif -#define H(x) (h[x]) -#define dH(x) (dh[x]) - - FOLDb; - -#undef M -#undef H -#undef dH -} - -static const sph_u64 final_b[16] = { - SPH_C64(0xaaaaaaaaaaaaaaa0), SPH_C64(0xaaaaaaaaaaaaaaa1), - SPH_C64(0xaaaaaaaaaaaaaaa2), SPH_C64(0xaaaaaaaaaaaaaaa3), - SPH_C64(0xaaaaaaaaaaaaaaa4), SPH_C64(0xaaaaaaaaaaaaaaa5), - SPH_C64(0xaaaaaaaaaaaaaaa6), SPH_C64(0xaaaaaaaaaaaaaaa7), - SPH_C64(0xaaaaaaaaaaaaaaa8), SPH_C64(0xaaaaaaaaaaaaaaa9), - SPH_C64(0xaaaaaaaaaaaaaaaa), SPH_C64(0xaaaaaaaaaaaaaaab), - SPH_C64(0xaaaaaaaaaaaaaaac), SPH_C64(0xaaaaaaaaaaaaaaad), - SPH_C64(0xaaaaaaaaaaaaaaae), SPH_C64(0xaaaaaaaaaaaaaaaf) -}; - -static void -bmw64_init(sph_bmw_big_context *sc, const sph_u64 *iv) -{ - memcpy(sc->H, iv, sizeof sc->H); - sc->ptr = 0; - sc->bit_count = 0; -} - -static void -bmw64(sph_bmw_big_context *sc, const void *data, size_t len) -{ - unsigned char *buf; - size_t ptr; - sph_u64 htmp[16]; - sph_u64 *h1, *h2; - - sc->bit_count += (sph_u64)len << 3; - buf = sc->buf; - ptr = sc->ptr; - h1 = sc->H; - h2 = htmp; - while (len > 0) { - size_t clen; - - clen = (sizeof sc->buf) - ptr; - if (clen > len) - clen = len; - memcpy(buf + ptr, data, clen); - data = (const unsigned char *)data + clen; - len -= clen; - ptr += clen; - if (ptr == sizeof sc->buf) { - sph_u64 *ht; - - compress_big(buf, h1, h2); - ht = h1; - h1 = h2; - h2 = ht; - ptr = 0; - } - } - sc->ptr = ptr; - if (h1 != sc->H) - memcpy(sc->H, h1, sizeof sc->H); -} - -static void -bmw64_close(sph_bmw_big_context *sc, unsigned ub, unsigned n, - void *dst, size_t out_size_w64) -{ - unsigned char *buf, *out; - size_t ptr, u, v; - unsigned z; - sph_u64 h1[16], h2[16], *h; - - buf = sc->buf; - ptr = sc->ptr; - z = 0x80 >> n; - buf[ptr ++] = ((ub & -z) | z) & 0xFF; - h = sc->H; - if (ptr > (sizeof sc->buf) - 8) { - memset(buf + ptr, 0, (sizeof sc->buf) - ptr); - compress_big(buf, h, h1); - ptr = 0; - h = h1; - } - memset(buf + ptr, 0, (sizeof sc->buf) - 8 - ptr); - sph_enc64le_aligned(buf + (sizeof sc->buf) - 8, - SPH_T64(sc->bit_count + n)); - compress_big(buf, h, h2); - for (u = 0; u < 16; u ++) - sph_enc64le_aligned(buf + 8 * u, h2[u]); - compress_big(buf, final_b, h1); - out = dst; - for (u = 0, v = 16 - out_size_w64; u < out_size_w64; u ++, v ++) - sph_enc64le(out + 8 * u, h1[v]); -} - -#endif - -/* see sph_bmw.h */ -void -sph_bmw224_init(void *cc) -{ - bmw32_init(cc, IV224); -} - -/* see sph_bmw.h */ -void -sph_bmw224(void *cc, const void *data, size_t len) -{ - bmw32(cc, data, len); -} - -/* see sph_bmw.h */ -void -sph_bmw224_close(void *cc, void *dst) -{ - sph_bmw224_addbits_and_close(cc, 0, 0, dst); -} - -/* see sph_bmw.h */ -void -sph_bmw224_addbits_and_close(void *cc, unsigned ub, unsigned n, void *dst) -{ - bmw32_close(cc, ub, n, dst, 7); - sph_bmw224_init(cc); -} - -/* see sph_bmw.h */ -void -sph_bmw256_init(void *cc) -{ - bmw32_init(cc, IV256); -} - -/* see sph_bmw.h */ -void -sph_bmw256(void *cc, const void *data, size_t len) -{ - bmw32(cc, data, len); -} - -/* see sph_bmw.h */ -void -sph_bmw256_close(void *cc, void *dst) -{ - sph_bmw256_addbits_and_close(cc, 0, 0, dst); -} - -/* see sph_bmw.h */ -void -sph_bmw256_addbits_and_close(void *cc, unsigned ub, unsigned n, void *dst) -{ - bmw32_close(cc, ub, n, dst, 8); - sph_bmw256_init(cc); -} - -#if SPH_64 - -/* see sph_bmw.h */ -void -sph_bmw384_init(void *cc) -{ - bmw64_init(cc, IV384); -} - -/* see sph_bmw.h */ -void -sph_bmw384(void *cc, const void *data, size_t len) -{ - bmw64(cc, data, len); -} - -/* see sph_bmw.h */ -void -sph_bmw384_close(void *cc, void *dst) -{ - sph_bmw384_addbits_and_close(cc, 0, 0, dst); -} - -/* see sph_bmw.h */ -void -sph_bmw384_addbits_and_close(void *cc, unsigned ub, unsigned n, void *dst) -{ - bmw64_close(cc, ub, n, dst, 6); - sph_bmw384_init(cc); -} - -/* see sph_bmw.h */ -void -sph_bmw512_init(void *cc) -{ - bmw64_init(cc, IV512); -} - -/* see sph_bmw.h */ -void -sph_bmw512(void *cc, const void *data, size_t len) -{ - bmw64(cc, data, len); -} - -/* see sph_bmw.h */ -void -sph_bmw512_close(void *cc, void *dst) -{ - sph_bmw512_addbits_and_close(cc, 0, 0, dst); -} - -/* see sph_bmw.h */ -void -sph_bmw512_addbits_and_close(void *cc, unsigned ub, unsigned n, void *dst) -{ - bmw64_close(cc, ub, n, dst, 8); - sph_bmw512_init(cc); -} - -#endif - -#ifdef __cplusplus -} -#endif diff --git a/src/crypto/cubehash.c b/src/crypto/cubehash.c deleted file mode 100644 index 9322fe14e055..000000000000 --- a/src/crypto/cubehash.c +++ /dev/null @@ -1,723 +0,0 @@ -/* $Id: cubehash.c 227 2010-06-16 17:28:38Z tp $ */ -/* - * CubeHash implementation. - * - * ==========================(LICENSE BEGIN)============================ - * - * Copyright (c) 2007-2010 Projet RNRT SAPHIR - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY - * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, - * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE - * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - * ===========================(LICENSE END)============================= - * - * @author Thomas Pornin - */ - -#include -#include -#include - -#include "sph_cubehash.h" -#ifdef __cplusplus -extern "C"{ -#endif - -#if SPH_SMALL_FOOTPRINT && !defined SPH_SMALL_FOOTPRINT_CUBEHASH -#define SPH_SMALL_FOOTPRINT_CUBEHASH 1 -#endif - -/* - * Some tests were conducted on an Intel Core2 Q6600 (32-bit and 64-bit - * mode), a PowerPC G3, and a MIPS-compatible CPU (Broadcom BCM3302). - * It appears that the optimal settings are: - * -- full unroll, no state copy on the "big" systems (x86, PowerPC) - * -- unroll to 4 or 8, state copy on the "small" system (MIPS) - */ - -#if SPH_SMALL_FOOTPRINT_CUBEHASH - -#if !defined SPH_CUBEHASH_UNROLL -#define SPH_CUBEHASH_UNROLL 4 -#endif -#if !defined SPH_CUBEHASH_NOCOPY -#define SPH_CUBEHASH_NOCOPY 1 -#endif - -#else - -#if !defined SPH_CUBEHASH_UNROLL -#define SPH_CUBEHASH_UNROLL 0 -#endif -#if !defined SPH_CUBEHASH_NOCOPY -#define SPH_CUBEHASH_NOCOPY 0 -#endif - -#endif - -#ifdef _MSC_VER -#pragma warning (disable: 4146) -#endif - -static const sph_u32 IV224[] = { - SPH_C32(0xB0FC8217), SPH_C32(0x1BEE1A90), SPH_C32(0x829E1A22), - SPH_C32(0x6362C342), SPH_C32(0x24D91C30), SPH_C32(0x03A7AA24), - SPH_C32(0xA63721C8), SPH_C32(0x85B0E2EF), SPH_C32(0xF35D13F3), - SPH_C32(0x41DA807D), SPH_C32(0x21A70CA6), SPH_C32(0x1F4E9774), - SPH_C32(0xB3E1C932), SPH_C32(0xEB0A79A8), SPH_C32(0xCDDAAA66), - SPH_C32(0xE2F6ECAA), SPH_C32(0x0A713362), SPH_C32(0xAA3080E0), - SPH_C32(0xD8F23A32), SPH_C32(0xCEF15E28), SPH_C32(0xDB086314), - SPH_C32(0x7F709DF7), SPH_C32(0xACD228A4), SPH_C32(0x704D6ECE), - SPH_C32(0xAA3EC95F), SPH_C32(0xE387C214), SPH_C32(0x3A6445FF), - SPH_C32(0x9CAB81C3), SPH_C32(0xC73D4B98), SPH_C32(0xD277AEBE), - SPH_C32(0xFD20151C), SPH_C32(0x00CB573E) -}; - -static const sph_u32 IV256[] = { - SPH_C32(0xEA2BD4B4), SPH_C32(0xCCD6F29F), SPH_C32(0x63117E71), - SPH_C32(0x35481EAE), SPH_C32(0x22512D5B), SPH_C32(0xE5D94E63), - SPH_C32(0x7E624131), SPH_C32(0xF4CC12BE), SPH_C32(0xC2D0B696), - SPH_C32(0x42AF2070), SPH_C32(0xD0720C35), SPH_C32(0x3361DA8C), - SPH_C32(0x28CCECA4), SPH_C32(0x8EF8AD83), SPH_C32(0x4680AC00), - SPH_C32(0x40E5FBAB), SPH_C32(0xD89041C3), SPH_C32(0x6107FBD5), - SPH_C32(0x6C859D41), SPH_C32(0xF0B26679), SPH_C32(0x09392549), - SPH_C32(0x5FA25603), SPH_C32(0x65C892FD), SPH_C32(0x93CB6285), - SPH_C32(0x2AF2B5AE), SPH_C32(0x9E4B4E60), SPH_C32(0x774ABFDD), - SPH_C32(0x85254725), SPH_C32(0x15815AEB), SPH_C32(0x4AB6AAD6), - SPH_C32(0x9CDAF8AF), SPH_C32(0xD6032C0A) -}; - -static const sph_u32 IV384[] = { - SPH_C32(0xE623087E), SPH_C32(0x04C00C87), SPH_C32(0x5EF46453), - SPH_C32(0x69524B13), SPH_C32(0x1A05C7A9), SPH_C32(0x3528DF88), - SPH_C32(0x6BDD01B5), SPH_C32(0x5057B792), SPH_C32(0x6AA7A922), - SPH_C32(0x649C7EEE), SPH_C32(0xF426309F), SPH_C32(0xCB629052), - SPH_C32(0xFC8E20ED), SPH_C32(0xB3482BAB), SPH_C32(0xF89E5E7E), - SPH_C32(0xD83D4DE4), SPH_C32(0x44BFC10D), SPH_C32(0x5FC1E63D), - SPH_C32(0x2104E6CB), SPH_C32(0x17958F7F), SPH_C32(0xDBEAEF70), - SPH_C32(0xB4B97E1E), SPH_C32(0x32C195F6), SPH_C32(0x6184A8E4), - SPH_C32(0x796C2543), SPH_C32(0x23DE176D), SPH_C32(0xD33BBAEC), - SPH_C32(0x0C12E5D2), SPH_C32(0x4EB95A7B), SPH_C32(0x2D18BA01), - SPH_C32(0x04EE475F), SPH_C32(0x1FC5F22E) -}; - -static const sph_u32 IV512[] = { - SPH_C32(0x2AEA2A61), SPH_C32(0x50F494D4), SPH_C32(0x2D538B8B), - SPH_C32(0x4167D83E), SPH_C32(0x3FEE2313), SPH_C32(0xC701CF8C), - SPH_C32(0xCC39968E), SPH_C32(0x50AC5695), SPH_C32(0x4D42C787), - SPH_C32(0xA647A8B3), SPH_C32(0x97CF0BEF), SPH_C32(0x825B4537), - SPH_C32(0xEEF864D2), SPH_C32(0xF22090C4), SPH_C32(0xD0E5CD33), - SPH_C32(0xA23911AE), SPH_C32(0xFCD398D9), SPH_C32(0x148FE485), - SPH_C32(0x1B017BEF), SPH_C32(0xB6444532), SPH_C32(0x6A536159), - SPH_C32(0x2FF5781C), SPH_C32(0x91FA7934), SPH_C32(0x0DBADEA9), - SPH_C32(0xD65C8A2B), SPH_C32(0xA5A70E75), SPH_C32(0xB1C62456), - SPH_C32(0xBC796576), SPH_C32(0x1921C8F7), SPH_C32(0xE7989AF1), - SPH_C32(0x7795D246), SPH_C32(0xD43E3B44) -}; - -#define T32 SPH_T32 -#define ROTL32 SPH_ROTL32 - -#if SPH_CUBEHASH_NOCOPY - -#define DECL_STATE -#define READ_STATE(cc) -#define WRITE_STATE(cc) - -#define x0 ((sc)->state[ 0]) -#define x1 ((sc)->state[ 1]) -#define x2 ((sc)->state[ 2]) -#define x3 ((sc)->state[ 3]) -#define x4 ((sc)->state[ 4]) -#define x5 ((sc)->state[ 5]) -#define x6 ((sc)->state[ 6]) -#define x7 ((sc)->state[ 7]) -#define x8 ((sc)->state[ 8]) -#define x9 ((sc)->state[ 9]) -#define xa ((sc)->state[10]) -#define xb ((sc)->state[11]) -#define xc ((sc)->state[12]) -#define xd ((sc)->state[13]) -#define xe ((sc)->state[14]) -#define xf ((sc)->state[15]) -#define xg ((sc)->state[16]) -#define xh ((sc)->state[17]) -#define xi ((sc)->state[18]) -#define xj ((sc)->state[19]) -#define xk ((sc)->state[20]) -#define xl ((sc)->state[21]) -#define xm ((sc)->state[22]) -#define xn ((sc)->state[23]) -#define xo ((sc)->state[24]) -#define xp ((sc)->state[25]) -#define xq ((sc)->state[26]) -#define xr ((sc)->state[27]) -#define xs ((sc)->state[28]) -#define xt ((sc)->state[29]) -#define xu ((sc)->state[30]) -#define xv ((sc)->state[31]) - -#else - -#define DECL_STATE \ - sph_u32 x0, x1, x2, x3, x4, x5, x6, x7; \ - sph_u32 x8, x9, xa, xb, xc, xd, xe, xf; \ - sph_u32 xg, xh, xi, xj, xk, xl, xm, xn; \ - sph_u32 xo, xp, xq, xr, xs, xt, xu, xv; - -#define READ_STATE(cc) do { \ - x0 = (cc)->state[ 0]; \ - x1 = (cc)->state[ 1]; \ - x2 = (cc)->state[ 2]; \ - x3 = (cc)->state[ 3]; \ - x4 = (cc)->state[ 4]; \ - x5 = (cc)->state[ 5]; \ - x6 = (cc)->state[ 6]; \ - x7 = (cc)->state[ 7]; \ - x8 = (cc)->state[ 8]; \ - x9 = (cc)->state[ 9]; \ - xa = (cc)->state[10]; \ - xb = (cc)->state[11]; \ - xc = (cc)->state[12]; \ - xd = (cc)->state[13]; \ - xe = (cc)->state[14]; \ - xf = (cc)->state[15]; \ - xg = (cc)->state[16]; \ - xh = (cc)->state[17]; \ - xi = (cc)->state[18]; \ - xj = (cc)->state[19]; \ - xk = (cc)->state[20]; \ - xl = (cc)->state[21]; \ - xm = (cc)->state[22]; \ - xn = (cc)->state[23]; \ - xo = (cc)->state[24]; \ - xp = (cc)->state[25]; \ - xq = (cc)->state[26]; \ - xr = (cc)->state[27]; \ - xs = (cc)->state[28]; \ - xt = (cc)->state[29]; \ - xu = (cc)->state[30]; \ - xv = (cc)->state[31]; \ - } while (0) - -#define WRITE_STATE(cc) do { \ - (cc)->state[ 0] = x0; \ - (cc)->state[ 1] = x1; \ - (cc)->state[ 2] = x2; \ - (cc)->state[ 3] = x3; \ - (cc)->state[ 4] = x4; \ - (cc)->state[ 5] = x5; \ - (cc)->state[ 6] = x6; \ - (cc)->state[ 7] = x7; \ - (cc)->state[ 8] = x8; \ - (cc)->state[ 9] = x9; \ - (cc)->state[10] = xa; \ - (cc)->state[11] = xb; \ - (cc)->state[12] = xc; \ - (cc)->state[13] = xd; \ - (cc)->state[14] = xe; \ - (cc)->state[15] = xf; \ - (cc)->state[16] = xg; \ - (cc)->state[17] = xh; \ - (cc)->state[18] = xi; \ - (cc)->state[19] = xj; \ - (cc)->state[20] = xk; \ - (cc)->state[21] = xl; \ - (cc)->state[22] = xm; \ - (cc)->state[23] = xn; \ - (cc)->state[24] = xo; \ - (cc)->state[25] = xp; \ - (cc)->state[26] = xq; \ - (cc)->state[27] = xr; \ - (cc)->state[28] = xs; \ - (cc)->state[29] = xt; \ - (cc)->state[30] = xu; \ - (cc)->state[31] = xv; \ - } while (0) - -#endif - -#define INPUT_BLOCK do { \ - x0 ^= sph_dec32le_aligned(buf + 0); \ - x1 ^= sph_dec32le_aligned(buf + 4); \ - x2 ^= sph_dec32le_aligned(buf + 8); \ - x3 ^= sph_dec32le_aligned(buf + 12); \ - x4 ^= sph_dec32le_aligned(buf + 16); \ - x5 ^= sph_dec32le_aligned(buf + 20); \ - x6 ^= sph_dec32le_aligned(buf + 24); \ - x7 ^= sph_dec32le_aligned(buf + 28); \ - } while (0) - -#define ROUND_EVEN do { \ - xg = T32(x0 + xg); \ - x0 = ROTL32(x0, 7); \ - xh = T32(x1 + xh); \ - x1 = ROTL32(x1, 7); \ - xi = T32(x2 + xi); \ - x2 = ROTL32(x2, 7); \ - xj = T32(x3 + xj); \ - x3 = ROTL32(x3, 7); \ - xk = T32(x4 + xk); \ - x4 = ROTL32(x4, 7); \ - xl = T32(x5 + xl); \ - x5 = ROTL32(x5, 7); \ - xm = T32(x6 + xm); \ - x6 = ROTL32(x6, 7); \ - xn = T32(x7 + xn); \ - x7 = ROTL32(x7, 7); \ - xo = T32(x8 + xo); \ - x8 = ROTL32(x8, 7); \ - xp = T32(x9 + xp); \ - x9 = ROTL32(x9, 7); \ - xq = T32(xa + xq); \ - xa = ROTL32(xa, 7); \ - xr = T32(xb + xr); \ - xb = ROTL32(xb, 7); \ - xs = T32(xc + xs); \ - xc = ROTL32(xc, 7); \ - xt = T32(xd + xt); \ - xd = ROTL32(xd, 7); \ - xu = T32(xe + xu); \ - xe = ROTL32(xe, 7); \ - xv = T32(xf + xv); \ - xf = ROTL32(xf, 7); \ - x8 ^= xg; \ - x9 ^= xh; \ - xa ^= xi; \ - xb ^= xj; \ - xc ^= xk; \ - xd ^= xl; \ - xe ^= xm; \ - xf ^= xn; \ - x0 ^= xo; \ - x1 ^= xp; \ - x2 ^= xq; \ - x3 ^= xr; \ - x4 ^= xs; \ - x5 ^= xt; \ - x6 ^= xu; \ - x7 ^= xv; \ - xi = T32(x8 + xi); \ - x8 = ROTL32(x8, 11); \ - xj = T32(x9 + xj); \ - x9 = ROTL32(x9, 11); \ - xg = T32(xa + xg); \ - xa = ROTL32(xa, 11); \ - xh = T32(xb + xh); \ - xb = ROTL32(xb, 11); \ - xm = T32(xc + xm); \ - xc = ROTL32(xc, 11); \ - xn = T32(xd + xn); \ - xd = ROTL32(xd, 11); \ - xk = T32(xe + xk); \ - xe = ROTL32(xe, 11); \ - xl = T32(xf + xl); \ - xf = ROTL32(xf, 11); \ - xq = T32(x0 + xq); \ - x0 = ROTL32(x0, 11); \ - xr = T32(x1 + xr); \ - x1 = ROTL32(x1, 11); \ - xo = T32(x2 + xo); \ - x2 = ROTL32(x2, 11); \ - xp = T32(x3 + xp); \ - x3 = ROTL32(x3, 11); \ - xu = T32(x4 + xu); \ - x4 = ROTL32(x4, 11); \ - xv = T32(x5 + xv); \ - x5 = ROTL32(x5, 11); \ - xs = T32(x6 + xs); \ - x6 = ROTL32(x6, 11); \ - xt = T32(x7 + xt); \ - x7 = ROTL32(x7, 11); \ - xc ^= xi; \ - xd ^= xj; \ - xe ^= xg; \ - xf ^= xh; \ - x8 ^= xm; \ - x9 ^= xn; \ - xa ^= xk; \ - xb ^= xl; \ - x4 ^= xq; \ - x5 ^= xr; \ - x6 ^= xo; \ - x7 ^= xp; \ - x0 ^= xu; \ - x1 ^= xv; \ - x2 ^= xs; \ - x3 ^= xt; \ - } while (0) - -#define ROUND_ODD do { \ - xj = T32(xc + xj); \ - xc = ROTL32(xc, 7); \ - xi = T32(xd + xi); \ - xd = ROTL32(xd, 7); \ - xh = T32(xe + xh); \ - xe = ROTL32(xe, 7); \ - xg = T32(xf + xg); \ - xf = ROTL32(xf, 7); \ - xn = T32(x8 + xn); \ - x8 = ROTL32(x8, 7); \ - xm = T32(x9 + xm); \ - x9 = ROTL32(x9, 7); \ - xl = T32(xa + xl); \ - xa = ROTL32(xa, 7); \ - xk = T32(xb + xk); \ - xb = ROTL32(xb, 7); \ - xr = T32(x4 + xr); \ - x4 = ROTL32(x4, 7); \ - xq = T32(x5 + xq); \ - x5 = ROTL32(x5, 7); \ - xp = T32(x6 + xp); \ - x6 = ROTL32(x6, 7); \ - xo = T32(x7 + xo); \ - x7 = ROTL32(x7, 7); \ - xv = T32(x0 + xv); \ - x0 = ROTL32(x0, 7); \ - xu = T32(x1 + xu); \ - x1 = ROTL32(x1, 7); \ - xt = T32(x2 + xt); \ - x2 = ROTL32(x2, 7); \ - xs = T32(x3 + xs); \ - x3 = ROTL32(x3, 7); \ - x4 ^= xj; \ - x5 ^= xi; \ - x6 ^= xh; \ - x7 ^= xg; \ - x0 ^= xn; \ - x1 ^= xm; \ - x2 ^= xl; \ - x3 ^= xk; \ - xc ^= xr; \ - xd ^= xq; \ - xe ^= xp; \ - xf ^= xo; \ - x8 ^= xv; \ - x9 ^= xu; \ - xa ^= xt; \ - xb ^= xs; \ - xh = T32(x4 + xh); \ - x4 = ROTL32(x4, 11); \ - xg = T32(x5 + xg); \ - x5 = ROTL32(x5, 11); \ - xj = T32(x6 + xj); \ - x6 = ROTL32(x6, 11); \ - xi = T32(x7 + xi); \ - x7 = ROTL32(x7, 11); \ - xl = T32(x0 + xl); \ - x0 = ROTL32(x0, 11); \ - xk = T32(x1 + xk); \ - x1 = ROTL32(x1, 11); \ - xn = T32(x2 + xn); \ - x2 = ROTL32(x2, 11); \ - xm = T32(x3 + xm); \ - x3 = ROTL32(x3, 11); \ - xp = T32(xc + xp); \ - xc = ROTL32(xc, 11); \ - xo = T32(xd + xo); \ - xd = ROTL32(xd, 11); \ - xr = T32(xe + xr); \ - xe = ROTL32(xe, 11); \ - xq = T32(xf + xq); \ - xf = ROTL32(xf, 11); \ - xt = T32(x8 + xt); \ - x8 = ROTL32(x8, 11); \ - xs = T32(x9 + xs); \ - x9 = ROTL32(x9, 11); \ - xv = T32(xa + xv); \ - xa = ROTL32(xa, 11); \ - xu = T32(xb + xu); \ - xb = ROTL32(xb, 11); \ - x0 ^= xh; \ - x1 ^= xg; \ - x2 ^= xj; \ - x3 ^= xi; \ - x4 ^= xl; \ - x5 ^= xk; \ - x6 ^= xn; \ - x7 ^= xm; \ - x8 ^= xp; \ - x9 ^= xo; \ - xa ^= xr; \ - xb ^= xq; \ - xc ^= xt; \ - xd ^= xs; \ - xe ^= xv; \ - xf ^= xu; \ - } while (0) - -/* - * There is no need to unroll all 16 rounds. The word-swapping permutation - * is an involution, so we need to unroll an even number of rounds. On - * "big" systems, unrolling 4 rounds yields about 97% of the speed - * achieved with full unrolling; and it keeps the code more compact - * for small architectures. - */ - -#if SPH_CUBEHASH_UNROLL == 2 - -#define SIXTEEN_ROUNDS do { \ - int j; \ - for (j = 0; j < 8; j ++) { \ - ROUND_EVEN; \ - ROUND_ODD; \ - } \ - } while (0) - -#elif SPH_CUBEHASH_UNROLL == 4 - -#define SIXTEEN_ROUNDS do { \ - int j; \ - for (j = 0; j < 4; j ++) { \ - ROUND_EVEN; \ - ROUND_ODD; \ - ROUND_EVEN; \ - ROUND_ODD; \ - } \ - } while (0) - -#elif SPH_CUBEHASH_UNROLL == 8 - -#define SIXTEEN_ROUNDS do { \ - int j; \ - for (j = 0; j < 2; j ++) { \ - ROUND_EVEN; \ - ROUND_ODD; \ - ROUND_EVEN; \ - ROUND_ODD; \ - ROUND_EVEN; \ - ROUND_ODD; \ - ROUND_EVEN; \ - ROUND_ODD; \ - } \ - } while (0) - -#else - -#define SIXTEEN_ROUNDS do { \ - ROUND_EVEN; \ - ROUND_ODD; \ - ROUND_EVEN; \ - ROUND_ODD; \ - ROUND_EVEN; \ - ROUND_ODD; \ - ROUND_EVEN; \ - ROUND_ODD; \ - ROUND_EVEN; \ - ROUND_ODD; \ - ROUND_EVEN; \ - ROUND_ODD; \ - ROUND_EVEN; \ - ROUND_ODD; \ - ROUND_EVEN; \ - ROUND_ODD; \ - } while (0) - -#endif - -static void -cubehash_init(sph_cubehash_context *sc, const sph_u32 *iv) -{ - memcpy(sc->state, iv, sizeof sc->state); - sc->ptr = 0; -} - -static void -cubehash_core(sph_cubehash_context *sc, const void *data, size_t len) -{ - unsigned char *buf; - size_t ptr; - DECL_STATE - - buf = sc->buf; - ptr = sc->ptr; - if (len < (sizeof sc->buf) - ptr) { - memcpy(buf + ptr, data, len); - ptr += len; - sc->ptr = ptr; - return; - } - - READ_STATE(sc); - while (len > 0) { - size_t clen; - - clen = (sizeof sc->buf) - ptr; - if (clen > len) - clen = len; - memcpy(buf + ptr, data, clen); - ptr += clen; - data = (const unsigned char *)data + clen; - len -= clen; - if (ptr == sizeof sc->buf) { - INPUT_BLOCK; - SIXTEEN_ROUNDS; - ptr = 0; - } - } - WRITE_STATE(sc); - sc->ptr = ptr; -} - -static void -cubehash_close(sph_cubehash_context *sc, unsigned ub, unsigned n, - void *dst, size_t out_size_w32) -{ - unsigned char *buf, *out; - size_t ptr; - unsigned z; - int i; - DECL_STATE - - buf = sc->buf; - ptr = sc->ptr; - z = 0x80 >> n; - buf[ptr ++] = ((ub & -z) | z) & 0xFF; - memset(buf + ptr, 0, (sizeof sc->buf) - ptr); - READ_STATE(sc); - INPUT_BLOCK; - for (i = 0; i < 11; i ++) { - SIXTEEN_ROUNDS; - if (i == 0) - xv ^= SPH_C32(1); - } - WRITE_STATE(sc); - out = dst; - for (z = 0; z < out_size_w32; z ++) - sph_enc32le(out + (z << 2), sc->state[z]); -} - -/* see sph_cubehash.h */ -void -sph_cubehash224_init(void *cc) -{ - cubehash_init(cc, IV224); -} - -/* see sph_cubehash.h */ -void -sph_cubehash224(void *cc, const void *data, size_t len) -{ - cubehash_core(cc, data, len); -} - -/* see sph_cubehash.h */ -void -sph_cubehash224_close(void *cc, void *dst) -{ - sph_cubehash224_addbits_and_close(cc, 0, 0, dst); -} - -/* see sph_cubehash.h */ -void -sph_cubehash224_addbits_and_close(void *cc, unsigned ub, unsigned n, void *dst) -{ - cubehash_close(cc, ub, n, dst, 7); - sph_cubehash224_init(cc); -} - -/* see sph_cubehash.h */ -void -sph_cubehash256_init(void *cc) -{ - cubehash_init(cc, IV256); -} - -/* see sph_cubehash.h */ -void -sph_cubehash256(void *cc, const void *data, size_t len) -{ - cubehash_core(cc, data, len); -} - -/* see sph_cubehash.h */ -void -sph_cubehash256_close(void *cc, void *dst) -{ - sph_cubehash256_addbits_and_close(cc, 0, 0, dst); -} - -/* see sph_cubehash.h */ -void -sph_cubehash256_addbits_and_close(void *cc, unsigned ub, unsigned n, void *dst) -{ - cubehash_close(cc, ub, n, dst, 8); - sph_cubehash256_init(cc); -} - -/* see sph_cubehash.h */ -void -sph_cubehash384_init(void *cc) -{ - cubehash_init(cc, IV384); -} - -/* see sph_cubehash.h */ -void -sph_cubehash384(void *cc, const void *data, size_t len) -{ - cubehash_core(cc, data, len); -} - -/* see sph_cubehash.h */ -void -sph_cubehash384_close(void *cc, void *dst) -{ - sph_cubehash384_addbits_and_close(cc, 0, 0, dst); -} - -/* see sph_cubehash.h */ -void -sph_cubehash384_addbits_and_close(void *cc, unsigned ub, unsigned n, void *dst) -{ - cubehash_close(cc, ub, n, dst, 12); - sph_cubehash384_init(cc); -} - -/* see sph_cubehash.h */ -void -sph_cubehash512_init(void *cc) -{ - cubehash_init(cc, IV512); -} - -/* see sph_cubehash.h */ -void -sph_cubehash512(void *cc, const void *data, size_t len) -{ - cubehash_core(cc, data, len); -} - -/* see sph_cubehash.h */ -void -sph_cubehash512_close(void *cc, void *dst) -{ - sph_cubehash512_addbits_and_close(cc, 0, 0, dst); -} - -/* see sph_cubehash.h */ -void -sph_cubehash512_addbits_and_close(void *cc, unsigned ub, unsigned n, void *dst) -{ - cubehash_close(cc, ub, n, dst, 16); - sph_cubehash512_init(cc); -} -#ifdef __cplusplus -} -#endif diff --git a/src/crypto/groestl.c b/src/crypto/groestl.c deleted file mode 100644 index 928bc41efab9..000000000000 --- a/src/crypto/groestl.c +++ /dev/null @@ -1,3123 +0,0 @@ -/* $Id: groestl.c 260 2011-07-21 01:02:38Z tp $ */ -/* - * Groestl implementation. - * - * ==========================(LICENSE BEGIN)============================ - * - * Copyright (c) 2007-2010 Projet RNRT SAPHIR - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY - * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, - * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE - * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - * ===========================(LICENSE END)============================= - * - * @author Thomas Pornin - */ - -#include -#include - -#include "sph_groestl.h" - -#ifdef __cplusplus -extern "C"{ -#endif - -#if SPH_SMALL_FOOTPRINT && !defined SPH_SMALL_FOOTPRINT_GROESTL -#define SPH_SMALL_FOOTPRINT_GROESTL 1 -#endif - -/* - * Apparently, the 32-bit-only version is not faster than the 64-bit - * version unless using the "small footprint" code on a 32-bit machine. - */ -#if !defined SPH_GROESTL_64 -#if SPH_SMALL_FOOTPRINT_GROESTL && !SPH_64_TRUE -#define SPH_GROESTL_64 0 -#else -#define SPH_GROESTL_64 1 -#endif -#endif - -#if !SPH_64 -#undef SPH_GROESTL_64 -#endif - -#ifdef _MSC_VER -#pragma warning (disable: 4146) -#endif - -/* - * The internal representation may use either big-endian or - * little-endian. Using the platform default representation speeds up - * encoding and decoding between bytes and the matrix columns. - */ - -#undef USE_LE -#if SPH_GROESTL_LITTLE_ENDIAN -#define USE_LE 1 -#elif SPH_GROESTL_BIG_ENDIAN -#define USE_LE 0 -#elif SPH_LITTLE_ENDIAN -#define USE_LE 1 -#endif - -#if USE_LE - -#define C32e(x) ((SPH_C32(x) >> 24) \ - | ((SPH_C32(x) >> 8) & SPH_C32(0x0000FF00)) \ - | ((SPH_C32(x) << 8) & SPH_C32(0x00FF0000)) \ - | ((SPH_C32(x) << 24) & SPH_C32(0xFF000000))) -#define dec32e_aligned sph_dec32le_aligned -#define enc32e sph_enc32le -#define B32_0(x) ((x) & 0xFF) -#define B32_1(x) (((x) >> 8) & 0xFF) -#define B32_2(x) (((x) >> 16) & 0xFF) -#define B32_3(x) ((x) >> 24) - -#define R32u(u, d) SPH_T32(((u) << 16) | ((d) >> 16)) -#define R32d(u, d) SPH_T32(((u) >> 16) | ((d) << 16)) - -#define PC32up(j, r) ((sph_u32)((j) + (r))) -#define PC32dn(j, r) 0 -#define QC32up(j, r) SPH_C32(0xFFFFFFFF) -#define QC32dn(j, r) (((sph_u32)(r) << 24) ^ SPH_T32(~((sph_u32)(j) << 24))) - -#if SPH_64 -#define C64e(x) ((SPH_C64(x) >> 56) \ - | ((SPH_C64(x) >> 40) & SPH_C64(0x000000000000FF00)) \ - | ((SPH_C64(x) >> 24) & SPH_C64(0x0000000000FF0000)) \ - | ((SPH_C64(x) >> 8) & SPH_C64(0x00000000FF000000)) \ - | ((SPH_C64(x) << 8) & SPH_C64(0x000000FF00000000)) \ - | ((SPH_C64(x) << 24) & SPH_C64(0x0000FF0000000000)) \ - | ((SPH_C64(x) << 40) & SPH_C64(0x00FF000000000000)) \ - | ((SPH_C64(x) << 56) & SPH_C64(0xFF00000000000000))) -#define dec64e_aligned sph_dec64le_aligned -#define enc64e sph_enc64le -#define B64_0(x) ((x) & 0xFF) -#define B64_1(x) (((x) >> 8) & 0xFF) -#define B64_2(x) (((x) >> 16) & 0xFF) -#define B64_3(x) (((x) >> 24) & 0xFF) -#define B64_4(x) (((x) >> 32) & 0xFF) -#define B64_5(x) (((x) >> 40) & 0xFF) -#define B64_6(x) (((x) >> 48) & 0xFF) -#define B64_7(x) ((x) >> 56) -#define R64 SPH_ROTL64 -#define PC64(j, r) ((sph_u64)((j) + (r))) -#define QC64(j, r) (((sph_u64)(r) << 56) ^ SPH_T64(~((sph_u64)(j) << 56))) -#endif - -#else - -#define C32e(x) SPH_C32(x) -#define dec32e_aligned sph_dec32be_aligned -#define enc32e sph_enc32be -#define B32_0(x) ((x) >> 24) -#define B32_1(x) (((x) >> 16) & 0xFF) -#define B32_2(x) (((x) >> 8) & 0xFF) -#define B32_3(x) ((x) & 0xFF) - -#define R32u(u, d) SPH_T32(((u) >> 16) | ((d) << 16)) -#define R32d(u, d) SPH_T32(((u) << 16) | ((d) >> 16)) - -#define PC32up(j, r) ((sph_u32)((j) + (r)) << 24) -#define PC32dn(j, r) 0 -#define QC32up(j, r) SPH_C32(0xFFFFFFFF) -#define QC32dn(j, r) ((sph_u32)(r) ^ SPH_T32(~(sph_u32)(j))) - -#if SPH_64 -#define C64e(x) SPH_C64(x) -#define dec64e_aligned sph_dec64be_aligned -#define enc64e sph_enc64be -#define B64_0(x) ((x) >> 56) -#define B64_1(x) (((x) >> 48) & 0xFF) -#define B64_2(x) (((x) >> 40) & 0xFF) -#define B64_3(x) (((x) >> 32) & 0xFF) -#define B64_4(x) (((x) >> 24) & 0xFF) -#define B64_5(x) (((x) >> 16) & 0xFF) -#define B64_6(x) (((x) >> 8) & 0xFF) -#define B64_7(x) ((x) & 0xFF) -#define R64 SPH_ROTR64 -#define PC64(j, r) ((sph_u64)((j) + (r)) << 56) -#define QC64(j, r) ((sph_u64)(r) ^ SPH_T64(~(sph_u64)(j))) -#endif - -#endif - -#if SPH_GROESTL_64 - -static const sph_u64 T0[] = { - C64e(0xc632f4a5f497a5c6), C64e(0xf86f978497eb84f8), - C64e(0xee5eb099b0c799ee), C64e(0xf67a8c8d8cf78df6), - C64e(0xffe8170d17e50dff), C64e(0xd60adcbddcb7bdd6), - C64e(0xde16c8b1c8a7b1de), C64e(0x916dfc54fc395491), - C64e(0x6090f050f0c05060), C64e(0x0207050305040302), - C64e(0xce2ee0a9e087a9ce), C64e(0x56d1877d87ac7d56), - C64e(0xe7cc2b192bd519e7), C64e(0xb513a662a67162b5), - C64e(0x4d7c31e6319ae64d), C64e(0xec59b59ab5c39aec), - C64e(0x8f40cf45cf05458f), C64e(0x1fa3bc9dbc3e9d1f), - C64e(0x8949c040c0094089), C64e(0xfa68928792ef87fa), - C64e(0xefd03f153fc515ef), C64e(0xb29426eb267febb2), - C64e(0x8ece40c94007c98e), C64e(0xfbe61d0b1ded0bfb), - C64e(0x416e2fec2f82ec41), C64e(0xb31aa967a97d67b3), - C64e(0x5f431cfd1cbefd5f), C64e(0x456025ea258aea45), - C64e(0x23f9dabfda46bf23), C64e(0x535102f702a6f753), - C64e(0xe445a196a1d396e4), C64e(0x9b76ed5bed2d5b9b), - C64e(0x75285dc25deac275), C64e(0xe1c5241c24d91ce1), - C64e(0x3dd4e9aee97aae3d), C64e(0x4cf2be6abe986a4c), - C64e(0x6c82ee5aeed85a6c), C64e(0x7ebdc341c3fc417e), - C64e(0xf5f3060206f102f5), C64e(0x8352d14fd11d4f83), - C64e(0x688ce45ce4d05c68), C64e(0x515607f407a2f451), - C64e(0xd18d5c345cb934d1), C64e(0xf9e1180818e908f9), - C64e(0xe24cae93aedf93e2), C64e(0xab3e9573954d73ab), - C64e(0x6297f553f5c45362), C64e(0x2a6b413f41543f2a), - C64e(0x081c140c14100c08), C64e(0x9563f652f6315295), - C64e(0x46e9af65af8c6546), C64e(0x9d7fe25ee2215e9d), - C64e(0x3048782878602830), C64e(0x37cff8a1f86ea137), - C64e(0x0a1b110f11140f0a), C64e(0x2febc4b5c45eb52f), - C64e(0x0e151b091b1c090e), C64e(0x247e5a365a483624), - C64e(0x1badb69bb6369b1b), C64e(0xdf98473d47a53ddf), - C64e(0xcda76a266a8126cd), C64e(0x4ef5bb69bb9c694e), - C64e(0x7f334ccd4cfecd7f), C64e(0xea50ba9fbacf9fea), - C64e(0x123f2d1b2d241b12), C64e(0x1da4b99eb93a9e1d), - C64e(0x58c49c749cb07458), C64e(0x3446722e72682e34), - C64e(0x3641772d776c2d36), C64e(0xdc11cdb2cda3b2dc), - C64e(0xb49d29ee2973eeb4), C64e(0x5b4d16fb16b6fb5b), - C64e(0xa4a501f60153f6a4), C64e(0x76a1d74dd7ec4d76), - C64e(0xb714a361a37561b7), C64e(0x7d3449ce49face7d), - C64e(0x52df8d7b8da47b52), C64e(0xdd9f423e42a13edd), - C64e(0x5ecd937193bc715e), C64e(0x13b1a297a2269713), - C64e(0xa6a204f50457f5a6), C64e(0xb901b868b86968b9), - C64e(0x0000000000000000), C64e(0xc1b5742c74992cc1), - C64e(0x40e0a060a0806040), C64e(0xe3c2211f21dd1fe3), - C64e(0x793a43c843f2c879), C64e(0xb69a2ced2c77edb6), - C64e(0xd40dd9bed9b3bed4), C64e(0x8d47ca46ca01468d), - C64e(0x671770d970ced967), C64e(0x72afdd4bdde44b72), - C64e(0x94ed79de7933de94), C64e(0x98ff67d4672bd498), - C64e(0xb09323e8237be8b0), C64e(0x855bde4ade114a85), - C64e(0xbb06bd6bbd6d6bbb), C64e(0xc5bb7e2a7e912ac5), - C64e(0x4f7b34e5349ee54f), C64e(0xedd73a163ac116ed), - C64e(0x86d254c55417c586), C64e(0x9af862d7622fd79a), - C64e(0x6699ff55ffcc5566), C64e(0x11b6a794a7229411), - C64e(0x8ac04acf4a0fcf8a), C64e(0xe9d9301030c910e9), - C64e(0x040e0a060a080604), C64e(0xfe66988198e781fe), - C64e(0xa0ab0bf00b5bf0a0), C64e(0x78b4cc44ccf04478), - C64e(0x25f0d5bad54aba25), C64e(0x4b753ee33e96e34b), - C64e(0xa2ac0ef30e5ff3a2), C64e(0x5d4419fe19bafe5d), - C64e(0x80db5bc05b1bc080), C64e(0x0580858a850a8a05), - C64e(0x3fd3ecadec7ead3f), C64e(0x21fedfbcdf42bc21), - C64e(0x70a8d848d8e04870), C64e(0xf1fd0c040cf904f1), - C64e(0x63197adf7ac6df63), C64e(0x772f58c158eec177), - C64e(0xaf309f759f4575af), C64e(0x42e7a563a5846342), - C64e(0x2070503050403020), C64e(0xe5cb2e1a2ed11ae5), - C64e(0xfdef120e12e10efd), C64e(0xbf08b76db7656dbf), - C64e(0x8155d44cd4194c81), C64e(0x18243c143c301418), - C64e(0x26795f355f4c3526), C64e(0xc3b2712f719d2fc3), - C64e(0xbe8638e13867e1be), C64e(0x35c8fda2fd6aa235), - C64e(0x88c74fcc4f0bcc88), C64e(0x2e654b394b5c392e), - C64e(0x936af957f93d5793), C64e(0x55580df20daaf255), - C64e(0xfc619d829de382fc), C64e(0x7ab3c947c9f4477a), - C64e(0xc827efacef8bacc8), C64e(0xba8832e7326fe7ba), - C64e(0x324f7d2b7d642b32), C64e(0xe642a495a4d795e6), - C64e(0xc03bfba0fb9ba0c0), C64e(0x19aab398b3329819), - C64e(0x9ef668d16827d19e), C64e(0xa322817f815d7fa3), - C64e(0x44eeaa66aa886644), C64e(0x54d6827e82a87e54), - C64e(0x3bdde6abe676ab3b), C64e(0x0b959e839e16830b), - C64e(0x8cc945ca4503ca8c), C64e(0xc7bc7b297b9529c7), - C64e(0x6b056ed36ed6d36b), C64e(0x286c443c44503c28), - C64e(0xa72c8b798b5579a7), C64e(0xbc813de23d63e2bc), - C64e(0x1631271d272c1d16), C64e(0xad379a769a4176ad), - C64e(0xdb964d3b4dad3bdb), C64e(0x649efa56fac85664), - C64e(0x74a6d24ed2e84e74), C64e(0x1436221e22281e14), - C64e(0x92e476db763fdb92), C64e(0x0c121e0a1e180a0c), - C64e(0x48fcb46cb4906c48), C64e(0xb88f37e4376be4b8), - C64e(0x9f78e75de7255d9f), C64e(0xbd0fb26eb2616ebd), - C64e(0x43692aef2a86ef43), C64e(0xc435f1a6f193a6c4), - C64e(0x39dae3a8e372a839), C64e(0x31c6f7a4f762a431), - C64e(0xd38a593759bd37d3), C64e(0xf274868b86ff8bf2), - C64e(0xd583563256b132d5), C64e(0x8b4ec543c50d438b), - C64e(0x6e85eb59ebdc596e), C64e(0xda18c2b7c2afb7da), - C64e(0x018e8f8c8f028c01), C64e(0xb11dac64ac7964b1), - C64e(0x9cf16dd26d23d29c), C64e(0x49723be03b92e049), - C64e(0xd81fc7b4c7abb4d8), C64e(0xacb915fa1543faac), - C64e(0xf3fa090709fd07f3), C64e(0xcfa06f256f8525cf), - C64e(0xca20eaafea8fafca), C64e(0xf47d898e89f38ef4), - C64e(0x476720e9208ee947), C64e(0x1038281828201810), - C64e(0x6f0b64d564ded56f), C64e(0xf073838883fb88f0), - C64e(0x4afbb16fb1946f4a), C64e(0x5cca967296b8725c), - C64e(0x38546c246c702438), C64e(0x575f08f108aef157), - C64e(0x732152c752e6c773), C64e(0x9764f351f3355197), - C64e(0xcbae6523658d23cb), C64e(0xa125847c84597ca1), - C64e(0xe857bf9cbfcb9ce8), C64e(0x3e5d6321637c213e), - C64e(0x96ea7cdd7c37dd96), C64e(0x611e7fdc7fc2dc61), - C64e(0x0d9c9186911a860d), C64e(0x0f9b9485941e850f), - C64e(0xe04bab90abdb90e0), C64e(0x7cbac642c6f8427c), - C64e(0x712657c457e2c471), C64e(0xcc29e5aae583aacc), - C64e(0x90e373d8733bd890), C64e(0x06090f050f0c0506), - C64e(0xf7f4030103f501f7), C64e(0x1c2a36123638121c), - C64e(0xc23cfea3fe9fa3c2), C64e(0x6a8be15fe1d45f6a), - C64e(0xaebe10f91047f9ae), C64e(0x69026bd06bd2d069), - C64e(0x17bfa891a82e9117), C64e(0x9971e858e8295899), - C64e(0x3a5369276974273a), C64e(0x27f7d0b9d04eb927), - C64e(0xd991483848a938d9), C64e(0xebde351335cd13eb), - C64e(0x2be5ceb3ce56b32b), C64e(0x2277553355443322), - C64e(0xd204d6bbd6bfbbd2), C64e(0xa9399070904970a9), - C64e(0x07878089800e8907), C64e(0x33c1f2a7f266a733), - C64e(0x2decc1b6c15ab62d), C64e(0x3c5a66226678223c), - C64e(0x15b8ad92ad2a9215), C64e(0xc9a96020608920c9), - C64e(0x875cdb49db154987), C64e(0xaab01aff1a4fffaa), - C64e(0x50d8887888a07850), C64e(0xa52b8e7a8e517aa5), - C64e(0x03898a8f8a068f03), C64e(0x594a13f813b2f859), - C64e(0x09929b809b128009), C64e(0x1a2339173934171a), - C64e(0x651075da75cada65), C64e(0xd784533153b531d7), - C64e(0x84d551c65113c684), C64e(0xd003d3b8d3bbb8d0), - C64e(0x82dc5ec35e1fc382), C64e(0x29e2cbb0cb52b029), - C64e(0x5ac3997799b4775a), C64e(0x1e2d3311333c111e), - C64e(0x7b3d46cb46f6cb7b), C64e(0xa8b71ffc1f4bfca8), - C64e(0x6d0c61d661dad66d), C64e(0x2c624e3a4e583a2c) -}; - -#if !SPH_SMALL_FOOTPRINT_GROESTL - -static const sph_u64 T1[] = { - C64e(0xc6c632f4a5f497a5), C64e(0xf8f86f978497eb84), - C64e(0xeeee5eb099b0c799), C64e(0xf6f67a8c8d8cf78d), - C64e(0xffffe8170d17e50d), C64e(0xd6d60adcbddcb7bd), - C64e(0xdede16c8b1c8a7b1), C64e(0x91916dfc54fc3954), - C64e(0x606090f050f0c050), C64e(0x0202070503050403), - C64e(0xcece2ee0a9e087a9), C64e(0x5656d1877d87ac7d), - C64e(0xe7e7cc2b192bd519), C64e(0xb5b513a662a67162), - C64e(0x4d4d7c31e6319ae6), C64e(0xecec59b59ab5c39a), - C64e(0x8f8f40cf45cf0545), C64e(0x1f1fa3bc9dbc3e9d), - C64e(0x898949c040c00940), C64e(0xfafa68928792ef87), - C64e(0xefefd03f153fc515), C64e(0xb2b29426eb267feb), - C64e(0x8e8ece40c94007c9), C64e(0xfbfbe61d0b1ded0b), - C64e(0x41416e2fec2f82ec), C64e(0xb3b31aa967a97d67), - C64e(0x5f5f431cfd1cbefd), C64e(0x45456025ea258aea), - C64e(0x2323f9dabfda46bf), C64e(0x53535102f702a6f7), - C64e(0xe4e445a196a1d396), C64e(0x9b9b76ed5bed2d5b), - C64e(0x7575285dc25deac2), C64e(0xe1e1c5241c24d91c), - C64e(0x3d3dd4e9aee97aae), C64e(0x4c4cf2be6abe986a), - C64e(0x6c6c82ee5aeed85a), C64e(0x7e7ebdc341c3fc41), - C64e(0xf5f5f3060206f102), C64e(0x838352d14fd11d4f), - C64e(0x68688ce45ce4d05c), C64e(0x51515607f407a2f4), - C64e(0xd1d18d5c345cb934), C64e(0xf9f9e1180818e908), - C64e(0xe2e24cae93aedf93), C64e(0xabab3e9573954d73), - C64e(0x626297f553f5c453), C64e(0x2a2a6b413f41543f), - C64e(0x08081c140c14100c), C64e(0x959563f652f63152), - C64e(0x4646e9af65af8c65), C64e(0x9d9d7fe25ee2215e), - C64e(0x3030487828786028), C64e(0x3737cff8a1f86ea1), - C64e(0x0a0a1b110f11140f), C64e(0x2f2febc4b5c45eb5), - C64e(0x0e0e151b091b1c09), C64e(0x24247e5a365a4836), - C64e(0x1b1badb69bb6369b), C64e(0xdfdf98473d47a53d), - C64e(0xcdcda76a266a8126), C64e(0x4e4ef5bb69bb9c69), - C64e(0x7f7f334ccd4cfecd), C64e(0xeaea50ba9fbacf9f), - C64e(0x12123f2d1b2d241b), C64e(0x1d1da4b99eb93a9e), - C64e(0x5858c49c749cb074), C64e(0x343446722e72682e), - C64e(0x363641772d776c2d), C64e(0xdcdc11cdb2cda3b2), - C64e(0xb4b49d29ee2973ee), C64e(0x5b5b4d16fb16b6fb), - C64e(0xa4a4a501f60153f6), C64e(0x7676a1d74dd7ec4d), - C64e(0xb7b714a361a37561), C64e(0x7d7d3449ce49face), - C64e(0x5252df8d7b8da47b), C64e(0xdddd9f423e42a13e), - C64e(0x5e5ecd937193bc71), C64e(0x1313b1a297a22697), - C64e(0xa6a6a204f50457f5), C64e(0xb9b901b868b86968), - C64e(0x0000000000000000), C64e(0xc1c1b5742c74992c), - C64e(0x4040e0a060a08060), C64e(0xe3e3c2211f21dd1f), - C64e(0x79793a43c843f2c8), C64e(0xb6b69a2ced2c77ed), - C64e(0xd4d40dd9bed9b3be), C64e(0x8d8d47ca46ca0146), - C64e(0x67671770d970ced9), C64e(0x7272afdd4bdde44b), - C64e(0x9494ed79de7933de), C64e(0x9898ff67d4672bd4), - C64e(0xb0b09323e8237be8), C64e(0x85855bde4ade114a), - C64e(0xbbbb06bd6bbd6d6b), C64e(0xc5c5bb7e2a7e912a), - C64e(0x4f4f7b34e5349ee5), C64e(0xededd73a163ac116), - C64e(0x8686d254c55417c5), C64e(0x9a9af862d7622fd7), - C64e(0x666699ff55ffcc55), C64e(0x1111b6a794a72294), - C64e(0x8a8ac04acf4a0fcf), C64e(0xe9e9d9301030c910), - C64e(0x04040e0a060a0806), C64e(0xfefe66988198e781), - C64e(0xa0a0ab0bf00b5bf0), C64e(0x7878b4cc44ccf044), - C64e(0x2525f0d5bad54aba), C64e(0x4b4b753ee33e96e3), - C64e(0xa2a2ac0ef30e5ff3), C64e(0x5d5d4419fe19bafe), - C64e(0x8080db5bc05b1bc0), C64e(0x050580858a850a8a), - C64e(0x3f3fd3ecadec7ead), C64e(0x2121fedfbcdf42bc), - C64e(0x7070a8d848d8e048), C64e(0xf1f1fd0c040cf904), - C64e(0x6363197adf7ac6df), C64e(0x77772f58c158eec1), - C64e(0xafaf309f759f4575), C64e(0x4242e7a563a58463), - C64e(0x2020705030504030), C64e(0xe5e5cb2e1a2ed11a), - C64e(0xfdfdef120e12e10e), C64e(0xbfbf08b76db7656d), - C64e(0x818155d44cd4194c), C64e(0x1818243c143c3014), - C64e(0x2626795f355f4c35), C64e(0xc3c3b2712f719d2f), - C64e(0xbebe8638e13867e1), C64e(0x3535c8fda2fd6aa2), - C64e(0x8888c74fcc4f0bcc), C64e(0x2e2e654b394b5c39), - C64e(0x93936af957f93d57), C64e(0x5555580df20daaf2), - C64e(0xfcfc619d829de382), C64e(0x7a7ab3c947c9f447), - C64e(0xc8c827efacef8bac), C64e(0xbaba8832e7326fe7), - C64e(0x32324f7d2b7d642b), C64e(0xe6e642a495a4d795), - C64e(0xc0c03bfba0fb9ba0), C64e(0x1919aab398b33298), - C64e(0x9e9ef668d16827d1), C64e(0xa3a322817f815d7f), - C64e(0x4444eeaa66aa8866), C64e(0x5454d6827e82a87e), - C64e(0x3b3bdde6abe676ab), C64e(0x0b0b959e839e1683), - C64e(0x8c8cc945ca4503ca), C64e(0xc7c7bc7b297b9529), - C64e(0x6b6b056ed36ed6d3), C64e(0x28286c443c44503c), - C64e(0xa7a72c8b798b5579), C64e(0xbcbc813de23d63e2), - C64e(0x161631271d272c1d), C64e(0xadad379a769a4176), - C64e(0xdbdb964d3b4dad3b), C64e(0x64649efa56fac856), - C64e(0x7474a6d24ed2e84e), C64e(0x141436221e22281e), - C64e(0x9292e476db763fdb), C64e(0x0c0c121e0a1e180a), - C64e(0x4848fcb46cb4906c), C64e(0xb8b88f37e4376be4), - C64e(0x9f9f78e75de7255d), C64e(0xbdbd0fb26eb2616e), - C64e(0x4343692aef2a86ef), C64e(0xc4c435f1a6f193a6), - C64e(0x3939dae3a8e372a8), C64e(0x3131c6f7a4f762a4), - C64e(0xd3d38a593759bd37), C64e(0xf2f274868b86ff8b), - C64e(0xd5d583563256b132), C64e(0x8b8b4ec543c50d43), - C64e(0x6e6e85eb59ebdc59), C64e(0xdada18c2b7c2afb7), - C64e(0x01018e8f8c8f028c), C64e(0xb1b11dac64ac7964), - C64e(0x9c9cf16dd26d23d2), C64e(0x4949723be03b92e0), - C64e(0xd8d81fc7b4c7abb4), C64e(0xacacb915fa1543fa), - C64e(0xf3f3fa090709fd07), C64e(0xcfcfa06f256f8525), - C64e(0xcaca20eaafea8faf), C64e(0xf4f47d898e89f38e), - C64e(0x47476720e9208ee9), C64e(0x1010382818282018), - C64e(0x6f6f0b64d564ded5), C64e(0xf0f073838883fb88), - C64e(0x4a4afbb16fb1946f), C64e(0x5c5cca967296b872), - C64e(0x3838546c246c7024), C64e(0x57575f08f108aef1), - C64e(0x73732152c752e6c7), C64e(0x979764f351f33551), - C64e(0xcbcbae6523658d23), C64e(0xa1a125847c84597c), - C64e(0xe8e857bf9cbfcb9c), C64e(0x3e3e5d6321637c21), - C64e(0x9696ea7cdd7c37dd), C64e(0x61611e7fdc7fc2dc), - C64e(0x0d0d9c9186911a86), C64e(0x0f0f9b9485941e85), - C64e(0xe0e04bab90abdb90), C64e(0x7c7cbac642c6f842), - C64e(0x71712657c457e2c4), C64e(0xcccc29e5aae583aa), - C64e(0x9090e373d8733bd8), C64e(0x0606090f050f0c05), - C64e(0xf7f7f4030103f501), C64e(0x1c1c2a3612363812), - C64e(0xc2c23cfea3fe9fa3), C64e(0x6a6a8be15fe1d45f), - C64e(0xaeaebe10f91047f9), C64e(0x6969026bd06bd2d0), - C64e(0x1717bfa891a82e91), C64e(0x999971e858e82958), - C64e(0x3a3a536927697427), C64e(0x2727f7d0b9d04eb9), - C64e(0xd9d991483848a938), C64e(0xebebde351335cd13), - C64e(0x2b2be5ceb3ce56b3), C64e(0x2222775533554433), - C64e(0xd2d204d6bbd6bfbb), C64e(0xa9a9399070904970), - C64e(0x0707878089800e89), C64e(0x3333c1f2a7f266a7), - C64e(0x2d2decc1b6c15ab6), C64e(0x3c3c5a6622667822), - C64e(0x1515b8ad92ad2a92), C64e(0xc9c9a96020608920), - C64e(0x87875cdb49db1549), C64e(0xaaaab01aff1a4fff), - C64e(0x5050d8887888a078), C64e(0xa5a52b8e7a8e517a), - C64e(0x0303898a8f8a068f), C64e(0x59594a13f813b2f8), - C64e(0x0909929b809b1280), C64e(0x1a1a233917393417), - C64e(0x65651075da75cada), C64e(0xd7d784533153b531), - C64e(0x8484d551c65113c6), C64e(0xd0d003d3b8d3bbb8), - C64e(0x8282dc5ec35e1fc3), C64e(0x2929e2cbb0cb52b0), - C64e(0x5a5ac3997799b477), C64e(0x1e1e2d3311333c11), - C64e(0x7b7b3d46cb46f6cb), C64e(0xa8a8b71ffc1f4bfc), - C64e(0x6d6d0c61d661dad6), C64e(0x2c2c624e3a4e583a) -}; - -static const sph_u64 T2[] = { - C64e(0xa5c6c632f4a5f497), C64e(0x84f8f86f978497eb), - C64e(0x99eeee5eb099b0c7), C64e(0x8df6f67a8c8d8cf7), - C64e(0x0dffffe8170d17e5), C64e(0xbdd6d60adcbddcb7), - C64e(0xb1dede16c8b1c8a7), C64e(0x5491916dfc54fc39), - C64e(0x50606090f050f0c0), C64e(0x0302020705030504), - C64e(0xa9cece2ee0a9e087), C64e(0x7d5656d1877d87ac), - C64e(0x19e7e7cc2b192bd5), C64e(0x62b5b513a662a671), - C64e(0xe64d4d7c31e6319a), C64e(0x9aecec59b59ab5c3), - C64e(0x458f8f40cf45cf05), C64e(0x9d1f1fa3bc9dbc3e), - C64e(0x40898949c040c009), C64e(0x87fafa68928792ef), - C64e(0x15efefd03f153fc5), C64e(0xebb2b29426eb267f), - C64e(0xc98e8ece40c94007), C64e(0x0bfbfbe61d0b1ded), - C64e(0xec41416e2fec2f82), C64e(0x67b3b31aa967a97d), - C64e(0xfd5f5f431cfd1cbe), C64e(0xea45456025ea258a), - C64e(0xbf2323f9dabfda46), C64e(0xf753535102f702a6), - C64e(0x96e4e445a196a1d3), C64e(0x5b9b9b76ed5bed2d), - C64e(0xc27575285dc25dea), C64e(0x1ce1e1c5241c24d9), - C64e(0xae3d3dd4e9aee97a), C64e(0x6a4c4cf2be6abe98), - C64e(0x5a6c6c82ee5aeed8), C64e(0x417e7ebdc341c3fc), - C64e(0x02f5f5f3060206f1), C64e(0x4f838352d14fd11d), - C64e(0x5c68688ce45ce4d0), C64e(0xf451515607f407a2), - C64e(0x34d1d18d5c345cb9), C64e(0x08f9f9e1180818e9), - C64e(0x93e2e24cae93aedf), C64e(0x73abab3e9573954d), - C64e(0x53626297f553f5c4), C64e(0x3f2a2a6b413f4154), - C64e(0x0c08081c140c1410), C64e(0x52959563f652f631), - C64e(0x654646e9af65af8c), C64e(0x5e9d9d7fe25ee221), - C64e(0x2830304878287860), C64e(0xa13737cff8a1f86e), - C64e(0x0f0a0a1b110f1114), C64e(0xb52f2febc4b5c45e), - C64e(0x090e0e151b091b1c), C64e(0x3624247e5a365a48), - C64e(0x9b1b1badb69bb636), C64e(0x3ddfdf98473d47a5), - C64e(0x26cdcda76a266a81), C64e(0x694e4ef5bb69bb9c), - C64e(0xcd7f7f334ccd4cfe), C64e(0x9feaea50ba9fbacf), - C64e(0x1b12123f2d1b2d24), C64e(0x9e1d1da4b99eb93a), - C64e(0x745858c49c749cb0), C64e(0x2e343446722e7268), - C64e(0x2d363641772d776c), C64e(0xb2dcdc11cdb2cda3), - C64e(0xeeb4b49d29ee2973), C64e(0xfb5b5b4d16fb16b6), - C64e(0xf6a4a4a501f60153), C64e(0x4d7676a1d74dd7ec), - C64e(0x61b7b714a361a375), C64e(0xce7d7d3449ce49fa), - C64e(0x7b5252df8d7b8da4), C64e(0x3edddd9f423e42a1), - C64e(0x715e5ecd937193bc), C64e(0x971313b1a297a226), - C64e(0xf5a6a6a204f50457), C64e(0x68b9b901b868b869), - C64e(0x0000000000000000), C64e(0x2cc1c1b5742c7499), - C64e(0x604040e0a060a080), C64e(0x1fe3e3c2211f21dd), - C64e(0xc879793a43c843f2), C64e(0xedb6b69a2ced2c77), - C64e(0xbed4d40dd9bed9b3), C64e(0x468d8d47ca46ca01), - C64e(0xd967671770d970ce), C64e(0x4b7272afdd4bdde4), - C64e(0xde9494ed79de7933), C64e(0xd49898ff67d4672b), - C64e(0xe8b0b09323e8237b), C64e(0x4a85855bde4ade11), - C64e(0x6bbbbb06bd6bbd6d), C64e(0x2ac5c5bb7e2a7e91), - C64e(0xe54f4f7b34e5349e), C64e(0x16ededd73a163ac1), - C64e(0xc58686d254c55417), C64e(0xd79a9af862d7622f), - C64e(0x55666699ff55ffcc), C64e(0x941111b6a794a722), - C64e(0xcf8a8ac04acf4a0f), C64e(0x10e9e9d9301030c9), - C64e(0x0604040e0a060a08), C64e(0x81fefe66988198e7), - C64e(0xf0a0a0ab0bf00b5b), C64e(0x447878b4cc44ccf0), - C64e(0xba2525f0d5bad54a), C64e(0xe34b4b753ee33e96), - C64e(0xf3a2a2ac0ef30e5f), C64e(0xfe5d5d4419fe19ba), - C64e(0xc08080db5bc05b1b), C64e(0x8a050580858a850a), - C64e(0xad3f3fd3ecadec7e), C64e(0xbc2121fedfbcdf42), - C64e(0x487070a8d848d8e0), C64e(0x04f1f1fd0c040cf9), - C64e(0xdf6363197adf7ac6), C64e(0xc177772f58c158ee), - C64e(0x75afaf309f759f45), C64e(0x634242e7a563a584), - C64e(0x3020207050305040), C64e(0x1ae5e5cb2e1a2ed1), - C64e(0x0efdfdef120e12e1), C64e(0x6dbfbf08b76db765), - C64e(0x4c818155d44cd419), C64e(0x141818243c143c30), - C64e(0x352626795f355f4c), C64e(0x2fc3c3b2712f719d), - C64e(0xe1bebe8638e13867), C64e(0xa23535c8fda2fd6a), - C64e(0xcc8888c74fcc4f0b), C64e(0x392e2e654b394b5c), - C64e(0x5793936af957f93d), C64e(0xf25555580df20daa), - C64e(0x82fcfc619d829de3), C64e(0x477a7ab3c947c9f4), - C64e(0xacc8c827efacef8b), C64e(0xe7baba8832e7326f), - C64e(0x2b32324f7d2b7d64), C64e(0x95e6e642a495a4d7), - C64e(0xa0c0c03bfba0fb9b), C64e(0x981919aab398b332), - C64e(0xd19e9ef668d16827), C64e(0x7fa3a322817f815d), - C64e(0x664444eeaa66aa88), C64e(0x7e5454d6827e82a8), - C64e(0xab3b3bdde6abe676), C64e(0x830b0b959e839e16), - C64e(0xca8c8cc945ca4503), C64e(0x29c7c7bc7b297b95), - C64e(0xd36b6b056ed36ed6), C64e(0x3c28286c443c4450), - C64e(0x79a7a72c8b798b55), C64e(0xe2bcbc813de23d63), - C64e(0x1d161631271d272c), C64e(0x76adad379a769a41), - C64e(0x3bdbdb964d3b4dad), C64e(0x5664649efa56fac8), - C64e(0x4e7474a6d24ed2e8), C64e(0x1e141436221e2228), - C64e(0xdb9292e476db763f), C64e(0x0a0c0c121e0a1e18), - C64e(0x6c4848fcb46cb490), C64e(0xe4b8b88f37e4376b), - C64e(0x5d9f9f78e75de725), C64e(0x6ebdbd0fb26eb261), - C64e(0xef4343692aef2a86), C64e(0xa6c4c435f1a6f193), - C64e(0xa83939dae3a8e372), C64e(0xa43131c6f7a4f762), - C64e(0x37d3d38a593759bd), C64e(0x8bf2f274868b86ff), - C64e(0x32d5d583563256b1), C64e(0x438b8b4ec543c50d), - C64e(0x596e6e85eb59ebdc), C64e(0xb7dada18c2b7c2af), - C64e(0x8c01018e8f8c8f02), C64e(0x64b1b11dac64ac79), - C64e(0xd29c9cf16dd26d23), C64e(0xe04949723be03b92), - C64e(0xb4d8d81fc7b4c7ab), C64e(0xfaacacb915fa1543), - C64e(0x07f3f3fa090709fd), C64e(0x25cfcfa06f256f85), - C64e(0xafcaca20eaafea8f), C64e(0x8ef4f47d898e89f3), - C64e(0xe947476720e9208e), C64e(0x1810103828182820), - C64e(0xd56f6f0b64d564de), C64e(0x88f0f073838883fb), - C64e(0x6f4a4afbb16fb194), C64e(0x725c5cca967296b8), - C64e(0x243838546c246c70), C64e(0xf157575f08f108ae), - C64e(0xc773732152c752e6), C64e(0x51979764f351f335), - C64e(0x23cbcbae6523658d), C64e(0x7ca1a125847c8459), - C64e(0x9ce8e857bf9cbfcb), C64e(0x213e3e5d6321637c), - C64e(0xdd9696ea7cdd7c37), C64e(0xdc61611e7fdc7fc2), - C64e(0x860d0d9c9186911a), C64e(0x850f0f9b9485941e), - C64e(0x90e0e04bab90abdb), C64e(0x427c7cbac642c6f8), - C64e(0xc471712657c457e2), C64e(0xaacccc29e5aae583), - C64e(0xd89090e373d8733b), C64e(0x050606090f050f0c), - C64e(0x01f7f7f4030103f5), C64e(0x121c1c2a36123638), - C64e(0xa3c2c23cfea3fe9f), C64e(0x5f6a6a8be15fe1d4), - C64e(0xf9aeaebe10f91047), C64e(0xd06969026bd06bd2), - C64e(0x911717bfa891a82e), C64e(0x58999971e858e829), - C64e(0x273a3a5369276974), C64e(0xb92727f7d0b9d04e), - C64e(0x38d9d991483848a9), C64e(0x13ebebde351335cd), - C64e(0xb32b2be5ceb3ce56), C64e(0x3322227755335544), - C64e(0xbbd2d204d6bbd6bf), C64e(0x70a9a93990709049), - C64e(0x890707878089800e), C64e(0xa73333c1f2a7f266), - C64e(0xb62d2decc1b6c15a), C64e(0x223c3c5a66226678), - C64e(0x921515b8ad92ad2a), C64e(0x20c9c9a960206089), - C64e(0x4987875cdb49db15), C64e(0xffaaaab01aff1a4f), - C64e(0x785050d8887888a0), C64e(0x7aa5a52b8e7a8e51), - C64e(0x8f0303898a8f8a06), C64e(0xf859594a13f813b2), - C64e(0x800909929b809b12), C64e(0x171a1a2339173934), - C64e(0xda65651075da75ca), C64e(0x31d7d784533153b5), - C64e(0xc68484d551c65113), C64e(0xb8d0d003d3b8d3bb), - C64e(0xc38282dc5ec35e1f), C64e(0xb02929e2cbb0cb52), - C64e(0x775a5ac3997799b4), C64e(0x111e1e2d3311333c), - C64e(0xcb7b7b3d46cb46f6), C64e(0xfca8a8b71ffc1f4b), - C64e(0xd66d6d0c61d661da), C64e(0x3a2c2c624e3a4e58) -}; - -static const sph_u64 T3[] = { - C64e(0x97a5c6c632f4a5f4), C64e(0xeb84f8f86f978497), - C64e(0xc799eeee5eb099b0), C64e(0xf78df6f67a8c8d8c), - C64e(0xe50dffffe8170d17), C64e(0xb7bdd6d60adcbddc), - C64e(0xa7b1dede16c8b1c8), C64e(0x395491916dfc54fc), - C64e(0xc050606090f050f0), C64e(0x0403020207050305), - C64e(0x87a9cece2ee0a9e0), C64e(0xac7d5656d1877d87), - C64e(0xd519e7e7cc2b192b), C64e(0x7162b5b513a662a6), - C64e(0x9ae64d4d7c31e631), C64e(0xc39aecec59b59ab5), - C64e(0x05458f8f40cf45cf), C64e(0x3e9d1f1fa3bc9dbc), - C64e(0x0940898949c040c0), C64e(0xef87fafa68928792), - C64e(0xc515efefd03f153f), C64e(0x7febb2b29426eb26), - C64e(0x07c98e8ece40c940), C64e(0xed0bfbfbe61d0b1d), - C64e(0x82ec41416e2fec2f), C64e(0x7d67b3b31aa967a9), - C64e(0xbefd5f5f431cfd1c), C64e(0x8aea45456025ea25), - C64e(0x46bf2323f9dabfda), C64e(0xa6f753535102f702), - C64e(0xd396e4e445a196a1), C64e(0x2d5b9b9b76ed5bed), - C64e(0xeac27575285dc25d), C64e(0xd91ce1e1c5241c24), - C64e(0x7aae3d3dd4e9aee9), C64e(0x986a4c4cf2be6abe), - C64e(0xd85a6c6c82ee5aee), C64e(0xfc417e7ebdc341c3), - C64e(0xf102f5f5f3060206), C64e(0x1d4f838352d14fd1), - C64e(0xd05c68688ce45ce4), C64e(0xa2f451515607f407), - C64e(0xb934d1d18d5c345c), C64e(0xe908f9f9e1180818), - C64e(0xdf93e2e24cae93ae), C64e(0x4d73abab3e957395), - C64e(0xc453626297f553f5), C64e(0x543f2a2a6b413f41), - C64e(0x100c08081c140c14), C64e(0x3152959563f652f6), - C64e(0x8c654646e9af65af), C64e(0x215e9d9d7fe25ee2), - C64e(0x6028303048782878), C64e(0x6ea13737cff8a1f8), - C64e(0x140f0a0a1b110f11), C64e(0x5eb52f2febc4b5c4), - C64e(0x1c090e0e151b091b), C64e(0x483624247e5a365a), - C64e(0x369b1b1badb69bb6), C64e(0xa53ddfdf98473d47), - C64e(0x8126cdcda76a266a), C64e(0x9c694e4ef5bb69bb), - C64e(0xfecd7f7f334ccd4c), C64e(0xcf9feaea50ba9fba), - C64e(0x241b12123f2d1b2d), C64e(0x3a9e1d1da4b99eb9), - C64e(0xb0745858c49c749c), C64e(0x682e343446722e72), - C64e(0x6c2d363641772d77), C64e(0xa3b2dcdc11cdb2cd), - C64e(0x73eeb4b49d29ee29), C64e(0xb6fb5b5b4d16fb16), - C64e(0x53f6a4a4a501f601), C64e(0xec4d7676a1d74dd7), - C64e(0x7561b7b714a361a3), C64e(0xface7d7d3449ce49), - C64e(0xa47b5252df8d7b8d), C64e(0xa13edddd9f423e42), - C64e(0xbc715e5ecd937193), C64e(0x26971313b1a297a2), - C64e(0x57f5a6a6a204f504), C64e(0x6968b9b901b868b8), - C64e(0x0000000000000000), C64e(0x992cc1c1b5742c74), - C64e(0x80604040e0a060a0), C64e(0xdd1fe3e3c2211f21), - C64e(0xf2c879793a43c843), C64e(0x77edb6b69a2ced2c), - C64e(0xb3bed4d40dd9bed9), C64e(0x01468d8d47ca46ca), - C64e(0xced967671770d970), C64e(0xe44b7272afdd4bdd), - C64e(0x33de9494ed79de79), C64e(0x2bd49898ff67d467), - C64e(0x7be8b0b09323e823), C64e(0x114a85855bde4ade), - C64e(0x6d6bbbbb06bd6bbd), C64e(0x912ac5c5bb7e2a7e), - C64e(0x9ee54f4f7b34e534), C64e(0xc116ededd73a163a), - C64e(0x17c58686d254c554), C64e(0x2fd79a9af862d762), - C64e(0xcc55666699ff55ff), C64e(0x22941111b6a794a7), - C64e(0x0fcf8a8ac04acf4a), C64e(0xc910e9e9d9301030), - C64e(0x080604040e0a060a), C64e(0xe781fefe66988198), - C64e(0x5bf0a0a0ab0bf00b), C64e(0xf0447878b4cc44cc), - C64e(0x4aba2525f0d5bad5), C64e(0x96e34b4b753ee33e), - C64e(0x5ff3a2a2ac0ef30e), C64e(0xbafe5d5d4419fe19), - C64e(0x1bc08080db5bc05b), C64e(0x0a8a050580858a85), - C64e(0x7ead3f3fd3ecadec), C64e(0x42bc2121fedfbcdf), - C64e(0xe0487070a8d848d8), C64e(0xf904f1f1fd0c040c), - C64e(0xc6df6363197adf7a), C64e(0xeec177772f58c158), - C64e(0x4575afaf309f759f), C64e(0x84634242e7a563a5), - C64e(0x4030202070503050), C64e(0xd11ae5e5cb2e1a2e), - C64e(0xe10efdfdef120e12), C64e(0x656dbfbf08b76db7), - C64e(0x194c818155d44cd4), C64e(0x30141818243c143c), - C64e(0x4c352626795f355f), C64e(0x9d2fc3c3b2712f71), - C64e(0x67e1bebe8638e138), C64e(0x6aa23535c8fda2fd), - C64e(0x0bcc8888c74fcc4f), C64e(0x5c392e2e654b394b), - C64e(0x3d5793936af957f9), C64e(0xaaf25555580df20d), - C64e(0xe382fcfc619d829d), C64e(0xf4477a7ab3c947c9), - C64e(0x8bacc8c827efacef), C64e(0x6fe7baba8832e732), - C64e(0x642b32324f7d2b7d), C64e(0xd795e6e642a495a4), - C64e(0x9ba0c0c03bfba0fb), C64e(0x32981919aab398b3), - C64e(0x27d19e9ef668d168), C64e(0x5d7fa3a322817f81), - C64e(0x88664444eeaa66aa), C64e(0xa87e5454d6827e82), - C64e(0x76ab3b3bdde6abe6), C64e(0x16830b0b959e839e), - C64e(0x03ca8c8cc945ca45), C64e(0x9529c7c7bc7b297b), - C64e(0xd6d36b6b056ed36e), C64e(0x503c28286c443c44), - C64e(0x5579a7a72c8b798b), C64e(0x63e2bcbc813de23d), - C64e(0x2c1d161631271d27), C64e(0x4176adad379a769a), - C64e(0xad3bdbdb964d3b4d), C64e(0xc85664649efa56fa), - C64e(0xe84e7474a6d24ed2), C64e(0x281e141436221e22), - C64e(0x3fdb9292e476db76), C64e(0x180a0c0c121e0a1e), - C64e(0x906c4848fcb46cb4), C64e(0x6be4b8b88f37e437), - C64e(0x255d9f9f78e75de7), C64e(0x616ebdbd0fb26eb2), - C64e(0x86ef4343692aef2a), C64e(0x93a6c4c435f1a6f1), - C64e(0x72a83939dae3a8e3), C64e(0x62a43131c6f7a4f7), - C64e(0xbd37d3d38a593759), C64e(0xff8bf2f274868b86), - C64e(0xb132d5d583563256), C64e(0x0d438b8b4ec543c5), - C64e(0xdc596e6e85eb59eb), C64e(0xafb7dada18c2b7c2), - C64e(0x028c01018e8f8c8f), C64e(0x7964b1b11dac64ac), - C64e(0x23d29c9cf16dd26d), C64e(0x92e04949723be03b), - C64e(0xabb4d8d81fc7b4c7), C64e(0x43faacacb915fa15), - C64e(0xfd07f3f3fa090709), C64e(0x8525cfcfa06f256f), - C64e(0x8fafcaca20eaafea), C64e(0xf38ef4f47d898e89), - C64e(0x8ee947476720e920), C64e(0x2018101038281828), - C64e(0xded56f6f0b64d564), C64e(0xfb88f0f073838883), - C64e(0x946f4a4afbb16fb1), C64e(0xb8725c5cca967296), - C64e(0x70243838546c246c), C64e(0xaef157575f08f108), - C64e(0xe6c773732152c752), C64e(0x3551979764f351f3), - C64e(0x8d23cbcbae652365), C64e(0x597ca1a125847c84), - C64e(0xcb9ce8e857bf9cbf), C64e(0x7c213e3e5d632163), - C64e(0x37dd9696ea7cdd7c), C64e(0xc2dc61611e7fdc7f), - C64e(0x1a860d0d9c918691), C64e(0x1e850f0f9b948594), - C64e(0xdb90e0e04bab90ab), C64e(0xf8427c7cbac642c6), - C64e(0xe2c471712657c457), C64e(0x83aacccc29e5aae5), - C64e(0x3bd89090e373d873), C64e(0x0c050606090f050f), - C64e(0xf501f7f7f4030103), C64e(0x38121c1c2a361236), - C64e(0x9fa3c2c23cfea3fe), C64e(0xd45f6a6a8be15fe1), - C64e(0x47f9aeaebe10f910), C64e(0xd2d06969026bd06b), - C64e(0x2e911717bfa891a8), C64e(0x2958999971e858e8), - C64e(0x74273a3a53692769), C64e(0x4eb92727f7d0b9d0), - C64e(0xa938d9d991483848), C64e(0xcd13ebebde351335), - C64e(0x56b32b2be5ceb3ce), C64e(0x4433222277553355), - C64e(0xbfbbd2d204d6bbd6), C64e(0x4970a9a939907090), - C64e(0x0e89070787808980), C64e(0x66a73333c1f2a7f2), - C64e(0x5ab62d2decc1b6c1), C64e(0x78223c3c5a662266), - C64e(0x2a921515b8ad92ad), C64e(0x8920c9c9a9602060), - C64e(0x154987875cdb49db), C64e(0x4fffaaaab01aff1a), - C64e(0xa0785050d8887888), C64e(0x517aa5a52b8e7a8e), - C64e(0x068f0303898a8f8a), C64e(0xb2f859594a13f813), - C64e(0x12800909929b809b), C64e(0x34171a1a23391739), - C64e(0xcada65651075da75), C64e(0xb531d7d784533153), - C64e(0x13c68484d551c651), C64e(0xbbb8d0d003d3b8d3), - C64e(0x1fc38282dc5ec35e), C64e(0x52b02929e2cbb0cb), - C64e(0xb4775a5ac3997799), C64e(0x3c111e1e2d331133), - C64e(0xf6cb7b7b3d46cb46), C64e(0x4bfca8a8b71ffc1f), - C64e(0xdad66d6d0c61d661), C64e(0x583a2c2c624e3a4e) -}; - -#endif - -static const sph_u64 T4[] = { - C64e(0xf497a5c6c632f4a5), C64e(0x97eb84f8f86f9784), - C64e(0xb0c799eeee5eb099), C64e(0x8cf78df6f67a8c8d), - C64e(0x17e50dffffe8170d), C64e(0xdcb7bdd6d60adcbd), - C64e(0xc8a7b1dede16c8b1), C64e(0xfc395491916dfc54), - C64e(0xf0c050606090f050), C64e(0x0504030202070503), - C64e(0xe087a9cece2ee0a9), C64e(0x87ac7d5656d1877d), - C64e(0x2bd519e7e7cc2b19), C64e(0xa67162b5b513a662), - C64e(0x319ae64d4d7c31e6), C64e(0xb5c39aecec59b59a), - C64e(0xcf05458f8f40cf45), C64e(0xbc3e9d1f1fa3bc9d), - C64e(0xc00940898949c040), C64e(0x92ef87fafa689287), - C64e(0x3fc515efefd03f15), C64e(0x267febb2b29426eb), - C64e(0x4007c98e8ece40c9), C64e(0x1ded0bfbfbe61d0b), - C64e(0x2f82ec41416e2fec), C64e(0xa97d67b3b31aa967), - C64e(0x1cbefd5f5f431cfd), C64e(0x258aea45456025ea), - C64e(0xda46bf2323f9dabf), C64e(0x02a6f753535102f7), - C64e(0xa1d396e4e445a196), C64e(0xed2d5b9b9b76ed5b), - C64e(0x5deac27575285dc2), C64e(0x24d91ce1e1c5241c), - C64e(0xe97aae3d3dd4e9ae), C64e(0xbe986a4c4cf2be6a), - C64e(0xeed85a6c6c82ee5a), C64e(0xc3fc417e7ebdc341), - C64e(0x06f102f5f5f30602), C64e(0xd11d4f838352d14f), - C64e(0xe4d05c68688ce45c), C64e(0x07a2f451515607f4), - C64e(0x5cb934d1d18d5c34), C64e(0x18e908f9f9e11808), - C64e(0xaedf93e2e24cae93), C64e(0x954d73abab3e9573), - C64e(0xf5c453626297f553), C64e(0x41543f2a2a6b413f), - C64e(0x14100c08081c140c), C64e(0xf63152959563f652), - C64e(0xaf8c654646e9af65), C64e(0xe2215e9d9d7fe25e), - C64e(0x7860283030487828), C64e(0xf86ea13737cff8a1), - C64e(0x11140f0a0a1b110f), C64e(0xc45eb52f2febc4b5), - C64e(0x1b1c090e0e151b09), C64e(0x5a483624247e5a36), - C64e(0xb6369b1b1badb69b), C64e(0x47a53ddfdf98473d), - C64e(0x6a8126cdcda76a26), C64e(0xbb9c694e4ef5bb69), - C64e(0x4cfecd7f7f334ccd), C64e(0xbacf9feaea50ba9f), - C64e(0x2d241b12123f2d1b), C64e(0xb93a9e1d1da4b99e), - C64e(0x9cb0745858c49c74), C64e(0x72682e343446722e), - C64e(0x776c2d363641772d), C64e(0xcda3b2dcdc11cdb2), - C64e(0x2973eeb4b49d29ee), C64e(0x16b6fb5b5b4d16fb), - C64e(0x0153f6a4a4a501f6), C64e(0xd7ec4d7676a1d74d), - C64e(0xa37561b7b714a361), C64e(0x49face7d7d3449ce), - C64e(0x8da47b5252df8d7b), C64e(0x42a13edddd9f423e), - C64e(0x93bc715e5ecd9371), C64e(0xa226971313b1a297), - C64e(0x0457f5a6a6a204f5), C64e(0xb86968b9b901b868), - C64e(0x0000000000000000), C64e(0x74992cc1c1b5742c), - C64e(0xa080604040e0a060), C64e(0x21dd1fe3e3c2211f), - C64e(0x43f2c879793a43c8), C64e(0x2c77edb6b69a2ced), - C64e(0xd9b3bed4d40dd9be), C64e(0xca01468d8d47ca46), - C64e(0x70ced967671770d9), C64e(0xdde44b7272afdd4b), - C64e(0x7933de9494ed79de), C64e(0x672bd49898ff67d4), - C64e(0x237be8b0b09323e8), C64e(0xde114a85855bde4a), - C64e(0xbd6d6bbbbb06bd6b), C64e(0x7e912ac5c5bb7e2a), - C64e(0x349ee54f4f7b34e5), C64e(0x3ac116ededd73a16), - C64e(0x5417c58686d254c5), C64e(0x622fd79a9af862d7), - C64e(0xffcc55666699ff55), C64e(0xa722941111b6a794), - C64e(0x4a0fcf8a8ac04acf), C64e(0x30c910e9e9d93010), - C64e(0x0a080604040e0a06), C64e(0x98e781fefe669881), - C64e(0x0b5bf0a0a0ab0bf0), C64e(0xccf0447878b4cc44), - C64e(0xd54aba2525f0d5ba), C64e(0x3e96e34b4b753ee3), - C64e(0x0e5ff3a2a2ac0ef3), C64e(0x19bafe5d5d4419fe), - C64e(0x5b1bc08080db5bc0), C64e(0x850a8a050580858a), - C64e(0xec7ead3f3fd3ecad), C64e(0xdf42bc2121fedfbc), - C64e(0xd8e0487070a8d848), C64e(0x0cf904f1f1fd0c04), - C64e(0x7ac6df6363197adf), C64e(0x58eec177772f58c1), - C64e(0x9f4575afaf309f75), C64e(0xa584634242e7a563), - C64e(0x5040302020705030), C64e(0x2ed11ae5e5cb2e1a), - C64e(0x12e10efdfdef120e), C64e(0xb7656dbfbf08b76d), - C64e(0xd4194c818155d44c), C64e(0x3c30141818243c14), - C64e(0x5f4c352626795f35), C64e(0x719d2fc3c3b2712f), - C64e(0x3867e1bebe8638e1), C64e(0xfd6aa23535c8fda2), - C64e(0x4f0bcc8888c74fcc), C64e(0x4b5c392e2e654b39), - C64e(0xf93d5793936af957), C64e(0x0daaf25555580df2), - C64e(0x9de382fcfc619d82), C64e(0xc9f4477a7ab3c947), - C64e(0xef8bacc8c827efac), C64e(0x326fe7baba8832e7), - C64e(0x7d642b32324f7d2b), C64e(0xa4d795e6e642a495), - C64e(0xfb9ba0c0c03bfba0), C64e(0xb332981919aab398), - C64e(0x6827d19e9ef668d1), C64e(0x815d7fa3a322817f), - C64e(0xaa88664444eeaa66), C64e(0x82a87e5454d6827e), - C64e(0xe676ab3b3bdde6ab), C64e(0x9e16830b0b959e83), - C64e(0x4503ca8c8cc945ca), C64e(0x7b9529c7c7bc7b29), - C64e(0x6ed6d36b6b056ed3), C64e(0x44503c28286c443c), - C64e(0x8b5579a7a72c8b79), C64e(0x3d63e2bcbc813de2), - C64e(0x272c1d161631271d), C64e(0x9a4176adad379a76), - C64e(0x4dad3bdbdb964d3b), C64e(0xfac85664649efa56), - C64e(0xd2e84e7474a6d24e), C64e(0x22281e141436221e), - C64e(0x763fdb9292e476db), C64e(0x1e180a0c0c121e0a), - C64e(0xb4906c4848fcb46c), C64e(0x376be4b8b88f37e4), - C64e(0xe7255d9f9f78e75d), C64e(0xb2616ebdbd0fb26e), - C64e(0x2a86ef4343692aef), C64e(0xf193a6c4c435f1a6), - C64e(0xe372a83939dae3a8), C64e(0xf762a43131c6f7a4), - C64e(0x59bd37d3d38a5937), C64e(0x86ff8bf2f274868b), - C64e(0x56b132d5d5835632), C64e(0xc50d438b8b4ec543), - C64e(0xebdc596e6e85eb59), C64e(0xc2afb7dada18c2b7), - C64e(0x8f028c01018e8f8c), C64e(0xac7964b1b11dac64), - C64e(0x6d23d29c9cf16dd2), C64e(0x3b92e04949723be0), - C64e(0xc7abb4d8d81fc7b4), C64e(0x1543faacacb915fa), - C64e(0x09fd07f3f3fa0907), C64e(0x6f8525cfcfa06f25), - C64e(0xea8fafcaca20eaaf), C64e(0x89f38ef4f47d898e), - C64e(0x208ee947476720e9), C64e(0x2820181010382818), - C64e(0x64ded56f6f0b64d5), C64e(0x83fb88f0f0738388), - C64e(0xb1946f4a4afbb16f), C64e(0x96b8725c5cca9672), - C64e(0x6c70243838546c24), C64e(0x08aef157575f08f1), - C64e(0x52e6c773732152c7), C64e(0xf33551979764f351), - C64e(0x658d23cbcbae6523), C64e(0x84597ca1a125847c), - C64e(0xbfcb9ce8e857bf9c), C64e(0x637c213e3e5d6321), - C64e(0x7c37dd9696ea7cdd), C64e(0x7fc2dc61611e7fdc), - C64e(0x911a860d0d9c9186), C64e(0x941e850f0f9b9485), - C64e(0xabdb90e0e04bab90), C64e(0xc6f8427c7cbac642), - C64e(0x57e2c471712657c4), C64e(0xe583aacccc29e5aa), - C64e(0x733bd89090e373d8), C64e(0x0f0c050606090f05), - C64e(0x03f501f7f7f40301), C64e(0x3638121c1c2a3612), - C64e(0xfe9fa3c2c23cfea3), C64e(0xe1d45f6a6a8be15f), - C64e(0x1047f9aeaebe10f9), C64e(0x6bd2d06969026bd0), - C64e(0xa82e911717bfa891), C64e(0xe82958999971e858), - C64e(0x6974273a3a536927), C64e(0xd04eb92727f7d0b9), - C64e(0x48a938d9d9914838), C64e(0x35cd13ebebde3513), - C64e(0xce56b32b2be5ceb3), C64e(0x5544332222775533), - C64e(0xd6bfbbd2d204d6bb), C64e(0x904970a9a9399070), - C64e(0x800e890707878089), C64e(0xf266a73333c1f2a7), - C64e(0xc15ab62d2decc1b6), C64e(0x6678223c3c5a6622), - C64e(0xad2a921515b8ad92), C64e(0x608920c9c9a96020), - C64e(0xdb154987875cdb49), C64e(0x1a4fffaaaab01aff), - C64e(0x88a0785050d88878), C64e(0x8e517aa5a52b8e7a), - C64e(0x8a068f0303898a8f), C64e(0x13b2f859594a13f8), - C64e(0x9b12800909929b80), C64e(0x3934171a1a233917), - C64e(0x75cada65651075da), C64e(0x53b531d7d7845331), - C64e(0x5113c68484d551c6), C64e(0xd3bbb8d0d003d3b8), - C64e(0x5e1fc38282dc5ec3), C64e(0xcb52b02929e2cbb0), - C64e(0x99b4775a5ac39977), C64e(0x333c111e1e2d3311), - C64e(0x46f6cb7b7b3d46cb), C64e(0x1f4bfca8a8b71ffc), - C64e(0x61dad66d6d0c61d6), C64e(0x4e583a2c2c624e3a) -}; - -#if !SPH_SMALL_FOOTPRINT_GROESTL - -static const sph_u64 T5[] = { - C64e(0xa5f497a5c6c632f4), C64e(0x8497eb84f8f86f97), - C64e(0x99b0c799eeee5eb0), C64e(0x8d8cf78df6f67a8c), - C64e(0x0d17e50dffffe817), C64e(0xbddcb7bdd6d60adc), - C64e(0xb1c8a7b1dede16c8), C64e(0x54fc395491916dfc), - C64e(0x50f0c050606090f0), C64e(0x0305040302020705), - C64e(0xa9e087a9cece2ee0), C64e(0x7d87ac7d5656d187), - C64e(0x192bd519e7e7cc2b), C64e(0x62a67162b5b513a6), - C64e(0xe6319ae64d4d7c31), C64e(0x9ab5c39aecec59b5), - C64e(0x45cf05458f8f40cf), C64e(0x9dbc3e9d1f1fa3bc), - C64e(0x40c00940898949c0), C64e(0x8792ef87fafa6892), - C64e(0x153fc515efefd03f), C64e(0xeb267febb2b29426), - C64e(0xc94007c98e8ece40), C64e(0x0b1ded0bfbfbe61d), - C64e(0xec2f82ec41416e2f), C64e(0x67a97d67b3b31aa9), - C64e(0xfd1cbefd5f5f431c), C64e(0xea258aea45456025), - C64e(0xbfda46bf2323f9da), C64e(0xf702a6f753535102), - C64e(0x96a1d396e4e445a1), C64e(0x5bed2d5b9b9b76ed), - C64e(0xc25deac27575285d), C64e(0x1c24d91ce1e1c524), - C64e(0xaee97aae3d3dd4e9), C64e(0x6abe986a4c4cf2be), - C64e(0x5aeed85a6c6c82ee), C64e(0x41c3fc417e7ebdc3), - C64e(0x0206f102f5f5f306), C64e(0x4fd11d4f838352d1), - C64e(0x5ce4d05c68688ce4), C64e(0xf407a2f451515607), - C64e(0x345cb934d1d18d5c), C64e(0x0818e908f9f9e118), - C64e(0x93aedf93e2e24cae), C64e(0x73954d73abab3e95), - C64e(0x53f5c453626297f5), C64e(0x3f41543f2a2a6b41), - C64e(0x0c14100c08081c14), C64e(0x52f63152959563f6), - C64e(0x65af8c654646e9af), C64e(0x5ee2215e9d9d7fe2), - C64e(0x2878602830304878), C64e(0xa1f86ea13737cff8), - C64e(0x0f11140f0a0a1b11), C64e(0xb5c45eb52f2febc4), - C64e(0x091b1c090e0e151b), C64e(0x365a483624247e5a), - C64e(0x9bb6369b1b1badb6), C64e(0x3d47a53ddfdf9847), - C64e(0x266a8126cdcda76a), C64e(0x69bb9c694e4ef5bb), - C64e(0xcd4cfecd7f7f334c), C64e(0x9fbacf9feaea50ba), - C64e(0x1b2d241b12123f2d), C64e(0x9eb93a9e1d1da4b9), - C64e(0x749cb0745858c49c), C64e(0x2e72682e34344672), - C64e(0x2d776c2d36364177), C64e(0xb2cda3b2dcdc11cd), - C64e(0xee2973eeb4b49d29), C64e(0xfb16b6fb5b5b4d16), - C64e(0xf60153f6a4a4a501), C64e(0x4dd7ec4d7676a1d7), - C64e(0x61a37561b7b714a3), C64e(0xce49face7d7d3449), - C64e(0x7b8da47b5252df8d), C64e(0x3e42a13edddd9f42), - C64e(0x7193bc715e5ecd93), C64e(0x97a226971313b1a2), - C64e(0xf50457f5a6a6a204), C64e(0x68b86968b9b901b8), - C64e(0x0000000000000000), C64e(0x2c74992cc1c1b574), - C64e(0x60a080604040e0a0), C64e(0x1f21dd1fe3e3c221), - C64e(0xc843f2c879793a43), C64e(0xed2c77edb6b69a2c), - C64e(0xbed9b3bed4d40dd9), C64e(0x46ca01468d8d47ca), - C64e(0xd970ced967671770), C64e(0x4bdde44b7272afdd), - C64e(0xde7933de9494ed79), C64e(0xd4672bd49898ff67), - C64e(0xe8237be8b0b09323), C64e(0x4ade114a85855bde), - C64e(0x6bbd6d6bbbbb06bd), C64e(0x2a7e912ac5c5bb7e), - C64e(0xe5349ee54f4f7b34), C64e(0x163ac116ededd73a), - C64e(0xc55417c58686d254), C64e(0xd7622fd79a9af862), - C64e(0x55ffcc55666699ff), C64e(0x94a722941111b6a7), - C64e(0xcf4a0fcf8a8ac04a), C64e(0x1030c910e9e9d930), - C64e(0x060a080604040e0a), C64e(0x8198e781fefe6698), - C64e(0xf00b5bf0a0a0ab0b), C64e(0x44ccf0447878b4cc), - C64e(0xbad54aba2525f0d5), C64e(0xe33e96e34b4b753e), - C64e(0xf30e5ff3a2a2ac0e), C64e(0xfe19bafe5d5d4419), - C64e(0xc05b1bc08080db5b), C64e(0x8a850a8a05058085), - C64e(0xadec7ead3f3fd3ec), C64e(0xbcdf42bc2121fedf), - C64e(0x48d8e0487070a8d8), C64e(0x040cf904f1f1fd0c), - C64e(0xdf7ac6df6363197a), C64e(0xc158eec177772f58), - C64e(0x759f4575afaf309f), C64e(0x63a584634242e7a5), - C64e(0x3050403020207050), C64e(0x1a2ed11ae5e5cb2e), - C64e(0x0e12e10efdfdef12), C64e(0x6db7656dbfbf08b7), - C64e(0x4cd4194c818155d4), C64e(0x143c30141818243c), - C64e(0x355f4c352626795f), C64e(0x2f719d2fc3c3b271), - C64e(0xe13867e1bebe8638), C64e(0xa2fd6aa23535c8fd), - C64e(0xcc4f0bcc8888c74f), C64e(0x394b5c392e2e654b), - C64e(0x57f93d5793936af9), C64e(0xf20daaf25555580d), - C64e(0x829de382fcfc619d), C64e(0x47c9f4477a7ab3c9), - C64e(0xacef8bacc8c827ef), C64e(0xe7326fe7baba8832), - C64e(0x2b7d642b32324f7d), C64e(0x95a4d795e6e642a4), - C64e(0xa0fb9ba0c0c03bfb), C64e(0x98b332981919aab3), - C64e(0xd16827d19e9ef668), C64e(0x7f815d7fa3a32281), - C64e(0x66aa88664444eeaa), C64e(0x7e82a87e5454d682), - C64e(0xabe676ab3b3bdde6), C64e(0x839e16830b0b959e), - C64e(0xca4503ca8c8cc945), C64e(0x297b9529c7c7bc7b), - C64e(0xd36ed6d36b6b056e), C64e(0x3c44503c28286c44), - C64e(0x798b5579a7a72c8b), C64e(0xe23d63e2bcbc813d), - C64e(0x1d272c1d16163127), C64e(0x769a4176adad379a), - C64e(0x3b4dad3bdbdb964d), C64e(0x56fac85664649efa), - C64e(0x4ed2e84e7474a6d2), C64e(0x1e22281e14143622), - C64e(0xdb763fdb9292e476), C64e(0x0a1e180a0c0c121e), - C64e(0x6cb4906c4848fcb4), C64e(0xe4376be4b8b88f37), - C64e(0x5de7255d9f9f78e7), C64e(0x6eb2616ebdbd0fb2), - C64e(0xef2a86ef4343692a), C64e(0xa6f193a6c4c435f1), - C64e(0xa8e372a83939dae3), C64e(0xa4f762a43131c6f7), - C64e(0x3759bd37d3d38a59), C64e(0x8b86ff8bf2f27486), - C64e(0x3256b132d5d58356), C64e(0x43c50d438b8b4ec5), - C64e(0x59ebdc596e6e85eb), C64e(0xb7c2afb7dada18c2), - C64e(0x8c8f028c01018e8f), C64e(0x64ac7964b1b11dac), - C64e(0xd26d23d29c9cf16d), C64e(0xe03b92e04949723b), - C64e(0xb4c7abb4d8d81fc7), C64e(0xfa1543faacacb915), - C64e(0x0709fd07f3f3fa09), C64e(0x256f8525cfcfa06f), - C64e(0xafea8fafcaca20ea), C64e(0x8e89f38ef4f47d89), - C64e(0xe9208ee947476720), C64e(0x1828201810103828), - C64e(0xd564ded56f6f0b64), C64e(0x8883fb88f0f07383), - C64e(0x6fb1946f4a4afbb1), C64e(0x7296b8725c5cca96), - C64e(0x246c70243838546c), C64e(0xf108aef157575f08), - C64e(0xc752e6c773732152), C64e(0x51f33551979764f3), - C64e(0x23658d23cbcbae65), C64e(0x7c84597ca1a12584), - C64e(0x9cbfcb9ce8e857bf), C64e(0x21637c213e3e5d63), - C64e(0xdd7c37dd9696ea7c), C64e(0xdc7fc2dc61611e7f), - C64e(0x86911a860d0d9c91), C64e(0x85941e850f0f9b94), - C64e(0x90abdb90e0e04bab), C64e(0x42c6f8427c7cbac6), - C64e(0xc457e2c471712657), C64e(0xaae583aacccc29e5), - C64e(0xd8733bd89090e373), C64e(0x050f0c050606090f), - C64e(0x0103f501f7f7f403), C64e(0x123638121c1c2a36), - C64e(0xa3fe9fa3c2c23cfe), C64e(0x5fe1d45f6a6a8be1), - C64e(0xf91047f9aeaebe10), C64e(0xd06bd2d06969026b), - C64e(0x91a82e911717bfa8), C64e(0x58e82958999971e8), - C64e(0x276974273a3a5369), C64e(0xb9d04eb92727f7d0), - C64e(0x3848a938d9d99148), C64e(0x1335cd13ebebde35), - C64e(0xb3ce56b32b2be5ce), C64e(0x3355443322227755), - C64e(0xbbd6bfbbd2d204d6), C64e(0x70904970a9a93990), - C64e(0x89800e8907078780), C64e(0xa7f266a73333c1f2), - C64e(0xb6c15ab62d2decc1), C64e(0x226678223c3c5a66), - C64e(0x92ad2a921515b8ad), C64e(0x20608920c9c9a960), - C64e(0x49db154987875cdb), C64e(0xff1a4fffaaaab01a), - C64e(0x7888a0785050d888), C64e(0x7a8e517aa5a52b8e), - C64e(0x8f8a068f0303898a), C64e(0xf813b2f859594a13), - C64e(0x809b12800909929b), C64e(0x173934171a1a2339), - C64e(0xda75cada65651075), C64e(0x3153b531d7d78453), - C64e(0xc65113c68484d551), C64e(0xb8d3bbb8d0d003d3), - C64e(0xc35e1fc38282dc5e), C64e(0xb0cb52b02929e2cb), - C64e(0x7799b4775a5ac399), C64e(0x11333c111e1e2d33), - C64e(0xcb46f6cb7b7b3d46), C64e(0xfc1f4bfca8a8b71f), - C64e(0xd661dad66d6d0c61), C64e(0x3a4e583a2c2c624e) -}; - -static const sph_u64 T6[] = { - C64e(0xf4a5f497a5c6c632), C64e(0x978497eb84f8f86f), - C64e(0xb099b0c799eeee5e), C64e(0x8c8d8cf78df6f67a), - C64e(0x170d17e50dffffe8), C64e(0xdcbddcb7bdd6d60a), - C64e(0xc8b1c8a7b1dede16), C64e(0xfc54fc395491916d), - C64e(0xf050f0c050606090), C64e(0x0503050403020207), - C64e(0xe0a9e087a9cece2e), C64e(0x877d87ac7d5656d1), - C64e(0x2b192bd519e7e7cc), C64e(0xa662a67162b5b513), - C64e(0x31e6319ae64d4d7c), C64e(0xb59ab5c39aecec59), - C64e(0xcf45cf05458f8f40), C64e(0xbc9dbc3e9d1f1fa3), - C64e(0xc040c00940898949), C64e(0x928792ef87fafa68), - C64e(0x3f153fc515efefd0), C64e(0x26eb267febb2b294), - C64e(0x40c94007c98e8ece), C64e(0x1d0b1ded0bfbfbe6), - C64e(0x2fec2f82ec41416e), C64e(0xa967a97d67b3b31a), - C64e(0x1cfd1cbefd5f5f43), C64e(0x25ea258aea454560), - C64e(0xdabfda46bf2323f9), C64e(0x02f702a6f7535351), - C64e(0xa196a1d396e4e445), C64e(0xed5bed2d5b9b9b76), - C64e(0x5dc25deac2757528), C64e(0x241c24d91ce1e1c5), - C64e(0xe9aee97aae3d3dd4), C64e(0xbe6abe986a4c4cf2), - C64e(0xee5aeed85a6c6c82), C64e(0xc341c3fc417e7ebd), - C64e(0x060206f102f5f5f3), C64e(0xd14fd11d4f838352), - C64e(0xe45ce4d05c68688c), C64e(0x07f407a2f4515156), - C64e(0x5c345cb934d1d18d), C64e(0x180818e908f9f9e1), - C64e(0xae93aedf93e2e24c), C64e(0x9573954d73abab3e), - C64e(0xf553f5c453626297), C64e(0x413f41543f2a2a6b), - C64e(0x140c14100c08081c), C64e(0xf652f63152959563), - C64e(0xaf65af8c654646e9), C64e(0xe25ee2215e9d9d7f), - C64e(0x7828786028303048), C64e(0xf8a1f86ea13737cf), - C64e(0x110f11140f0a0a1b), C64e(0xc4b5c45eb52f2feb), - C64e(0x1b091b1c090e0e15), C64e(0x5a365a483624247e), - C64e(0xb69bb6369b1b1bad), C64e(0x473d47a53ddfdf98), - C64e(0x6a266a8126cdcda7), C64e(0xbb69bb9c694e4ef5), - C64e(0x4ccd4cfecd7f7f33), C64e(0xba9fbacf9feaea50), - C64e(0x2d1b2d241b12123f), C64e(0xb99eb93a9e1d1da4), - C64e(0x9c749cb0745858c4), C64e(0x722e72682e343446), - C64e(0x772d776c2d363641), C64e(0xcdb2cda3b2dcdc11), - C64e(0x29ee2973eeb4b49d), C64e(0x16fb16b6fb5b5b4d), - C64e(0x01f60153f6a4a4a5), C64e(0xd74dd7ec4d7676a1), - C64e(0xa361a37561b7b714), C64e(0x49ce49face7d7d34), - C64e(0x8d7b8da47b5252df), C64e(0x423e42a13edddd9f), - C64e(0x937193bc715e5ecd), C64e(0xa297a226971313b1), - C64e(0x04f50457f5a6a6a2), C64e(0xb868b86968b9b901), - C64e(0x0000000000000000), C64e(0x742c74992cc1c1b5), - C64e(0xa060a080604040e0), C64e(0x211f21dd1fe3e3c2), - C64e(0x43c843f2c879793a), C64e(0x2ced2c77edb6b69a), - C64e(0xd9bed9b3bed4d40d), C64e(0xca46ca01468d8d47), - C64e(0x70d970ced9676717), C64e(0xdd4bdde44b7272af), - C64e(0x79de7933de9494ed), C64e(0x67d4672bd49898ff), - C64e(0x23e8237be8b0b093), C64e(0xde4ade114a85855b), - C64e(0xbd6bbd6d6bbbbb06), C64e(0x7e2a7e912ac5c5bb), - C64e(0x34e5349ee54f4f7b), C64e(0x3a163ac116ededd7), - C64e(0x54c55417c58686d2), C64e(0x62d7622fd79a9af8), - C64e(0xff55ffcc55666699), C64e(0xa794a722941111b6), - C64e(0x4acf4a0fcf8a8ac0), C64e(0x301030c910e9e9d9), - C64e(0x0a060a080604040e), C64e(0x988198e781fefe66), - C64e(0x0bf00b5bf0a0a0ab), C64e(0xcc44ccf0447878b4), - C64e(0xd5bad54aba2525f0), C64e(0x3ee33e96e34b4b75), - C64e(0x0ef30e5ff3a2a2ac), C64e(0x19fe19bafe5d5d44), - C64e(0x5bc05b1bc08080db), C64e(0x858a850a8a050580), - C64e(0xecadec7ead3f3fd3), C64e(0xdfbcdf42bc2121fe), - C64e(0xd848d8e0487070a8), C64e(0x0c040cf904f1f1fd), - C64e(0x7adf7ac6df636319), C64e(0x58c158eec177772f), - C64e(0x9f759f4575afaf30), C64e(0xa563a584634242e7), - C64e(0x5030504030202070), C64e(0x2e1a2ed11ae5e5cb), - C64e(0x120e12e10efdfdef), C64e(0xb76db7656dbfbf08), - C64e(0xd44cd4194c818155), C64e(0x3c143c3014181824), - C64e(0x5f355f4c35262679), C64e(0x712f719d2fc3c3b2), - C64e(0x38e13867e1bebe86), C64e(0xfda2fd6aa23535c8), - C64e(0x4fcc4f0bcc8888c7), C64e(0x4b394b5c392e2e65), - C64e(0xf957f93d5793936a), C64e(0x0df20daaf2555558), - C64e(0x9d829de382fcfc61), C64e(0xc947c9f4477a7ab3), - C64e(0xefacef8bacc8c827), C64e(0x32e7326fe7baba88), - C64e(0x7d2b7d642b32324f), C64e(0xa495a4d795e6e642), - C64e(0xfba0fb9ba0c0c03b), C64e(0xb398b332981919aa), - C64e(0x68d16827d19e9ef6), C64e(0x817f815d7fa3a322), - C64e(0xaa66aa88664444ee), C64e(0x827e82a87e5454d6), - C64e(0xe6abe676ab3b3bdd), C64e(0x9e839e16830b0b95), - C64e(0x45ca4503ca8c8cc9), C64e(0x7b297b9529c7c7bc), - C64e(0x6ed36ed6d36b6b05), C64e(0x443c44503c28286c), - C64e(0x8b798b5579a7a72c), C64e(0x3de23d63e2bcbc81), - C64e(0x271d272c1d161631), C64e(0x9a769a4176adad37), - C64e(0x4d3b4dad3bdbdb96), C64e(0xfa56fac85664649e), - C64e(0xd24ed2e84e7474a6), C64e(0x221e22281e141436), - C64e(0x76db763fdb9292e4), C64e(0x1e0a1e180a0c0c12), - C64e(0xb46cb4906c4848fc), C64e(0x37e4376be4b8b88f), - C64e(0xe75de7255d9f9f78), C64e(0xb26eb2616ebdbd0f), - C64e(0x2aef2a86ef434369), C64e(0xf1a6f193a6c4c435), - C64e(0xe3a8e372a83939da), C64e(0xf7a4f762a43131c6), - C64e(0x593759bd37d3d38a), C64e(0x868b86ff8bf2f274), - C64e(0x563256b132d5d583), C64e(0xc543c50d438b8b4e), - C64e(0xeb59ebdc596e6e85), C64e(0xc2b7c2afb7dada18), - C64e(0x8f8c8f028c01018e), C64e(0xac64ac7964b1b11d), - C64e(0x6dd26d23d29c9cf1), C64e(0x3be03b92e0494972), - C64e(0xc7b4c7abb4d8d81f), C64e(0x15fa1543faacacb9), - C64e(0x090709fd07f3f3fa), C64e(0x6f256f8525cfcfa0), - C64e(0xeaafea8fafcaca20), C64e(0x898e89f38ef4f47d), - C64e(0x20e9208ee9474767), C64e(0x2818282018101038), - C64e(0x64d564ded56f6f0b), C64e(0x838883fb88f0f073), - C64e(0xb16fb1946f4a4afb), C64e(0x967296b8725c5cca), - C64e(0x6c246c7024383854), C64e(0x08f108aef157575f), - C64e(0x52c752e6c7737321), C64e(0xf351f33551979764), - C64e(0x6523658d23cbcbae), C64e(0x847c84597ca1a125), - C64e(0xbf9cbfcb9ce8e857), C64e(0x6321637c213e3e5d), - C64e(0x7cdd7c37dd9696ea), C64e(0x7fdc7fc2dc61611e), - C64e(0x9186911a860d0d9c), C64e(0x9485941e850f0f9b), - C64e(0xab90abdb90e0e04b), C64e(0xc642c6f8427c7cba), - C64e(0x57c457e2c4717126), C64e(0xe5aae583aacccc29), - C64e(0x73d8733bd89090e3), C64e(0x0f050f0c05060609), - C64e(0x030103f501f7f7f4), C64e(0x36123638121c1c2a), - C64e(0xfea3fe9fa3c2c23c), C64e(0xe15fe1d45f6a6a8b), - C64e(0x10f91047f9aeaebe), C64e(0x6bd06bd2d0696902), - C64e(0xa891a82e911717bf), C64e(0xe858e82958999971), - C64e(0x69276974273a3a53), C64e(0xd0b9d04eb92727f7), - C64e(0x483848a938d9d991), C64e(0x351335cd13ebebde), - C64e(0xceb3ce56b32b2be5), C64e(0x5533554433222277), - C64e(0xd6bbd6bfbbd2d204), C64e(0x9070904970a9a939), - C64e(0x8089800e89070787), C64e(0xf2a7f266a73333c1), - C64e(0xc1b6c15ab62d2dec), C64e(0x66226678223c3c5a), - C64e(0xad92ad2a921515b8), C64e(0x6020608920c9c9a9), - C64e(0xdb49db154987875c), C64e(0x1aff1a4fffaaaab0), - C64e(0x887888a0785050d8), C64e(0x8e7a8e517aa5a52b), - C64e(0x8a8f8a068f030389), C64e(0x13f813b2f859594a), - C64e(0x9b809b1280090992), C64e(0x39173934171a1a23), - C64e(0x75da75cada656510), C64e(0x533153b531d7d784), - C64e(0x51c65113c68484d5), C64e(0xd3b8d3bbb8d0d003), - C64e(0x5ec35e1fc38282dc), C64e(0xcbb0cb52b02929e2), - C64e(0x997799b4775a5ac3), C64e(0x3311333c111e1e2d), - C64e(0x46cb46f6cb7b7b3d), C64e(0x1ffc1f4bfca8a8b7), - C64e(0x61d661dad66d6d0c), C64e(0x4e3a4e583a2c2c62) -}; - -static const sph_u64 T7[] = { - C64e(0x32f4a5f497a5c6c6), C64e(0x6f978497eb84f8f8), - C64e(0x5eb099b0c799eeee), C64e(0x7a8c8d8cf78df6f6), - C64e(0xe8170d17e50dffff), C64e(0x0adcbddcb7bdd6d6), - C64e(0x16c8b1c8a7b1dede), C64e(0x6dfc54fc39549191), - C64e(0x90f050f0c0506060), C64e(0x0705030504030202), - C64e(0x2ee0a9e087a9cece), C64e(0xd1877d87ac7d5656), - C64e(0xcc2b192bd519e7e7), C64e(0x13a662a67162b5b5), - C64e(0x7c31e6319ae64d4d), C64e(0x59b59ab5c39aecec), - C64e(0x40cf45cf05458f8f), C64e(0xa3bc9dbc3e9d1f1f), - C64e(0x49c040c009408989), C64e(0x68928792ef87fafa), - C64e(0xd03f153fc515efef), C64e(0x9426eb267febb2b2), - C64e(0xce40c94007c98e8e), C64e(0xe61d0b1ded0bfbfb), - C64e(0x6e2fec2f82ec4141), C64e(0x1aa967a97d67b3b3), - C64e(0x431cfd1cbefd5f5f), C64e(0x6025ea258aea4545), - C64e(0xf9dabfda46bf2323), C64e(0x5102f702a6f75353), - C64e(0x45a196a1d396e4e4), C64e(0x76ed5bed2d5b9b9b), - C64e(0x285dc25deac27575), C64e(0xc5241c24d91ce1e1), - C64e(0xd4e9aee97aae3d3d), C64e(0xf2be6abe986a4c4c), - C64e(0x82ee5aeed85a6c6c), C64e(0xbdc341c3fc417e7e), - C64e(0xf3060206f102f5f5), C64e(0x52d14fd11d4f8383), - C64e(0x8ce45ce4d05c6868), C64e(0x5607f407a2f45151), - C64e(0x8d5c345cb934d1d1), C64e(0xe1180818e908f9f9), - C64e(0x4cae93aedf93e2e2), C64e(0x3e9573954d73abab), - C64e(0x97f553f5c4536262), C64e(0x6b413f41543f2a2a), - C64e(0x1c140c14100c0808), C64e(0x63f652f631529595), - C64e(0xe9af65af8c654646), C64e(0x7fe25ee2215e9d9d), - C64e(0x4878287860283030), C64e(0xcff8a1f86ea13737), - C64e(0x1b110f11140f0a0a), C64e(0xebc4b5c45eb52f2f), - C64e(0x151b091b1c090e0e), C64e(0x7e5a365a48362424), - C64e(0xadb69bb6369b1b1b), C64e(0x98473d47a53ddfdf), - C64e(0xa76a266a8126cdcd), C64e(0xf5bb69bb9c694e4e), - C64e(0x334ccd4cfecd7f7f), C64e(0x50ba9fbacf9feaea), - C64e(0x3f2d1b2d241b1212), C64e(0xa4b99eb93a9e1d1d), - C64e(0xc49c749cb0745858), C64e(0x46722e72682e3434), - C64e(0x41772d776c2d3636), C64e(0x11cdb2cda3b2dcdc), - C64e(0x9d29ee2973eeb4b4), C64e(0x4d16fb16b6fb5b5b), - C64e(0xa501f60153f6a4a4), C64e(0xa1d74dd7ec4d7676), - C64e(0x14a361a37561b7b7), C64e(0x3449ce49face7d7d), - C64e(0xdf8d7b8da47b5252), C64e(0x9f423e42a13edddd), - C64e(0xcd937193bc715e5e), C64e(0xb1a297a226971313), - C64e(0xa204f50457f5a6a6), C64e(0x01b868b86968b9b9), - C64e(0x0000000000000000), C64e(0xb5742c74992cc1c1), - C64e(0xe0a060a080604040), C64e(0xc2211f21dd1fe3e3), - C64e(0x3a43c843f2c87979), C64e(0x9a2ced2c77edb6b6), - C64e(0x0dd9bed9b3bed4d4), C64e(0x47ca46ca01468d8d), - C64e(0x1770d970ced96767), C64e(0xafdd4bdde44b7272), - C64e(0xed79de7933de9494), C64e(0xff67d4672bd49898), - C64e(0x9323e8237be8b0b0), C64e(0x5bde4ade114a8585), - C64e(0x06bd6bbd6d6bbbbb), C64e(0xbb7e2a7e912ac5c5), - C64e(0x7b34e5349ee54f4f), C64e(0xd73a163ac116eded), - C64e(0xd254c55417c58686), C64e(0xf862d7622fd79a9a), - C64e(0x99ff55ffcc556666), C64e(0xb6a794a722941111), - C64e(0xc04acf4a0fcf8a8a), C64e(0xd9301030c910e9e9), - C64e(0x0e0a060a08060404), C64e(0x66988198e781fefe), - C64e(0xab0bf00b5bf0a0a0), C64e(0xb4cc44ccf0447878), - C64e(0xf0d5bad54aba2525), C64e(0x753ee33e96e34b4b), - C64e(0xac0ef30e5ff3a2a2), C64e(0x4419fe19bafe5d5d), - C64e(0xdb5bc05b1bc08080), C64e(0x80858a850a8a0505), - C64e(0xd3ecadec7ead3f3f), C64e(0xfedfbcdf42bc2121), - C64e(0xa8d848d8e0487070), C64e(0xfd0c040cf904f1f1), - C64e(0x197adf7ac6df6363), C64e(0x2f58c158eec17777), - C64e(0x309f759f4575afaf), C64e(0xe7a563a584634242), - C64e(0x7050305040302020), C64e(0xcb2e1a2ed11ae5e5), - C64e(0xef120e12e10efdfd), C64e(0x08b76db7656dbfbf), - C64e(0x55d44cd4194c8181), C64e(0x243c143c30141818), - C64e(0x795f355f4c352626), C64e(0xb2712f719d2fc3c3), - C64e(0x8638e13867e1bebe), C64e(0xc8fda2fd6aa23535), - C64e(0xc74fcc4f0bcc8888), C64e(0x654b394b5c392e2e), - C64e(0x6af957f93d579393), C64e(0x580df20daaf25555), - C64e(0x619d829de382fcfc), C64e(0xb3c947c9f4477a7a), - C64e(0x27efacef8bacc8c8), C64e(0x8832e7326fe7baba), - C64e(0x4f7d2b7d642b3232), C64e(0x42a495a4d795e6e6), - C64e(0x3bfba0fb9ba0c0c0), C64e(0xaab398b332981919), - C64e(0xf668d16827d19e9e), C64e(0x22817f815d7fa3a3), - C64e(0xeeaa66aa88664444), C64e(0xd6827e82a87e5454), - C64e(0xdde6abe676ab3b3b), C64e(0x959e839e16830b0b), - C64e(0xc945ca4503ca8c8c), C64e(0xbc7b297b9529c7c7), - C64e(0x056ed36ed6d36b6b), C64e(0x6c443c44503c2828), - C64e(0x2c8b798b5579a7a7), C64e(0x813de23d63e2bcbc), - C64e(0x31271d272c1d1616), C64e(0x379a769a4176adad), - C64e(0x964d3b4dad3bdbdb), C64e(0x9efa56fac8566464), - C64e(0xa6d24ed2e84e7474), C64e(0x36221e22281e1414), - C64e(0xe476db763fdb9292), C64e(0x121e0a1e180a0c0c), - C64e(0xfcb46cb4906c4848), C64e(0x8f37e4376be4b8b8), - C64e(0x78e75de7255d9f9f), C64e(0x0fb26eb2616ebdbd), - C64e(0x692aef2a86ef4343), C64e(0x35f1a6f193a6c4c4), - C64e(0xdae3a8e372a83939), C64e(0xc6f7a4f762a43131), - C64e(0x8a593759bd37d3d3), C64e(0x74868b86ff8bf2f2), - C64e(0x83563256b132d5d5), C64e(0x4ec543c50d438b8b), - C64e(0x85eb59ebdc596e6e), C64e(0x18c2b7c2afb7dada), - C64e(0x8e8f8c8f028c0101), C64e(0x1dac64ac7964b1b1), - C64e(0xf16dd26d23d29c9c), C64e(0x723be03b92e04949), - C64e(0x1fc7b4c7abb4d8d8), C64e(0xb915fa1543faacac), - C64e(0xfa090709fd07f3f3), C64e(0xa06f256f8525cfcf), - C64e(0x20eaafea8fafcaca), C64e(0x7d898e89f38ef4f4), - C64e(0x6720e9208ee94747), C64e(0x3828182820181010), - C64e(0x0b64d564ded56f6f), C64e(0x73838883fb88f0f0), - C64e(0xfbb16fb1946f4a4a), C64e(0xca967296b8725c5c), - C64e(0x546c246c70243838), C64e(0x5f08f108aef15757), - C64e(0x2152c752e6c77373), C64e(0x64f351f335519797), - C64e(0xae6523658d23cbcb), C64e(0x25847c84597ca1a1), - C64e(0x57bf9cbfcb9ce8e8), C64e(0x5d6321637c213e3e), - C64e(0xea7cdd7c37dd9696), C64e(0x1e7fdc7fc2dc6161), - C64e(0x9c9186911a860d0d), C64e(0x9b9485941e850f0f), - C64e(0x4bab90abdb90e0e0), C64e(0xbac642c6f8427c7c), - C64e(0x2657c457e2c47171), C64e(0x29e5aae583aacccc), - C64e(0xe373d8733bd89090), C64e(0x090f050f0c050606), - C64e(0xf4030103f501f7f7), C64e(0x2a36123638121c1c), - C64e(0x3cfea3fe9fa3c2c2), C64e(0x8be15fe1d45f6a6a), - C64e(0xbe10f91047f9aeae), C64e(0x026bd06bd2d06969), - C64e(0xbfa891a82e911717), C64e(0x71e858e829589999), - C64e(0x5369276974273a3a), C64e(0xf7d0b9d04eb92727), - C64e(0x91483848a938d9d9), C64e(0xde351335cd13ebeb), - C64e(0xe5ceb3ce56b32b2b), C64e(0x7755335544332222), - C64e(0x04d6bbd6bfbbd2d2), C64e(0x399070904970a9a9), - C64e(0x878089800e890707), C64e(0xc1f2a7f266a73333), - C64e(0xecc1b6c15ab62d2d), C64e(0x5a66226678223c3c), - C64e(0xb8ad92ad2a921515), C64e(0xa96020608920c9c9), - C64e(0x5cdb49db15498787), C64e(0xb01aff1a4fffaaaa), - C64e(0xd8887888a0785050), C64e(0x2b8e7a8e517aa5a5), - C64e(0x898a8f8a068f0303), C64e(0x4a13f813b2f85959), - C64e(0x929b809b12800909), C64e(0x2339173934171a1a), - C64e(0x1075da75cada6565), C64e(0x84533153b531d7d7), - C64e(0xd551c65113c68484), C64e(0x03d3b8d3bbb8d0d0), - C64e(0xdc5ec35e1fc38282), C64e(0xe2cbb0cb52b02929), - C64e(0xc3997799b4775a5a), C64e(0x2d3311333c111e1e), - C64e(0x3d46cb46f6cb7b7b), C64e(0xb71ffc1f4bfca8a8), - C64e(0x0c61d661dad66d6d), C64e(0x624e3a4e583a2c2c) -}; - -#endif - -#define DECL_STATE_SMALL \ - sph_u64 H[8]; - -#define READ_STATE_SMALL(sc) do { \ - memcpy(H, (sc)->state.wide, sizeof H); \ - } while (0) - -#define WRITE_STATE_SMALL(sc) do { \ - memcpy((sc)->state.wide, H, sizeof H); \ - } while (0) - -#if SPH_SMALL_FOOTPRINT_GROESTL - -#define RSTT(d, a, b0, b1, b2, b3, b4, b5, b6, b7) do { \ - t[d] = T0[B64_0(a[b0])] \ - ^ R64(T0[B64_1(a[b1])], 8) \ - ^ R64(T0[B64_2(a[b2])], 16) \ - ^ R64(T0[B64_3(a[b3])], 24) \ - ^ T4[B64_4(a[b4])] \ - ^ R64(T4[B64_5(a[b5])], 8) \ - ^ R64(T4[B64_6(a[b6])], 16) \ - ^ R64(T4[B64_7(a[b7])], 24); \ - } while (0) - -#else - -#define RSTT(d, a, b0, b1, b2, b3, b4, b5, b6, b7) do { \ - t[d] = T0[B64_0(a[b0])] \ - ^ T1[B64_1(a[b1])] \ - ^ T2[B64_2(a[b2])] \ - ^ T3[B64_3(a[b3])] \ - ^ T4[B64_4(a[b4])] \ - ^ T5[B64_5(a[b5])] \ - ^ T6[B64_6(a[b6])] \ - ^ T7[B64_7(a[b7])]; \ - } while (0) - -#endif - -#define ROUND_SMALL_P(a, r) do { \ - sph_u64 t[8]; \ - a[0] ^= PC64(0x00, r); \ - a[1] ^= PC64(0x10, r); \ - a[2] ^= PC64(0x20, r); \ - a[3] ^= PC64(0x30, r); \ - a[4] ^= PC64(0x40, r); \ - a[5] ^= PC64(0x50, r); \ - a[6] ^= PC64(0x60, r); \ - a[7] ^= PC64(0x70, r); \ - RSTT(0, a, 0, 1, 2, 3, 4, 5, 6, 7); \ - RSTT(1, a, 1, 2, 3, 4, 5, 6, 7, 0); \ - RSTT(2, a, 2, 3, 4, 5, 6, 7, 0, 1); \ - RSTT(3, a, 3, 4, 5, 6, 7, 0, 1, 2); \ - RSTT(4, a, 4, 5, 6, 7, 0, 1, 2, 3); \ - RSTT(5, a, 5, 6, 7, 0, 1, 2, 3, 4); \ - RSTT(6, a, 6, 7, 0, 1, 2, 3, 4, 5); \ - RSTT(7, a, 7, 0, 1, 2, 3, 4, 5, 6); \ - a[0] = t[0]; \ - a[1] = t[1]; \ - a[2] = t[2]; \ - a[3] = t[3]; \ - a[4] = t[4]; \ - a[5] = t[5]; \ - a[6] = t[6]; \ - a[7] = t[7]; \ - } while (0) - -#define ROUND_SMALL_Q(a, r) do { \ - sph_u64 t[8]; \ - a[0] ^= QC64(0x00, r); \ - a[1] ^= QC64(0x10, r); \ - a[2] ^= QC64(0x20, r); \ - a[3] ^= QC64(0x30, r); \ - a[4] ^= QC64(0x40, r); \ - a[5] ^= QC64(0x50, r); \ - a[6] ^= QC64(0x60, r); \ - a[7] ^= QC64(0x70, r); \ - RSTT(0, a, 1, 3, 5, 7, 0, 2, 4, 6); \ - RSTT(1, a, 2, 4, 6, 0, 1, 3, 5, 7); \ - RSTT(2, a, 3, 5, 7, 1, 2, 4, 6, 0); \ - RSTT(3, a, 4, 6, 0, 2, 3, 5, 7, 1); \ - RSTT(4, a, 5, 7, 1, 3, 4, 6, 0, 2); \ - RSTT(5, a, 6, 0, 2, 4, 5, 7, 1, 3); \ - RSTT(6, a, 7, 1, 3, 5, 6, 0, 2, 4); \ - RSTT(7, a, 0, 2, 4, 6, 7, 1, 3, 5); \ - a[0] = t[0]; \ - a[1] = t[1]; \ - a[2] = t[2]; \ - a[3] = t[3]; \ - a[4] = t[4]; \ - a[5] = t[5]; \ - a[6] = t[6]; \ - a[7] = t[7]; \ - } while (0) - -#if SPH_SMALL_FOOTPRINT_GROESTL - -#define PERM_SMALL_P(a) do { \ - int r; \ - for (r = 0; r < 10; r ++) \ - ROUND_SMALL_P(a, r); \ - } while (0) - -#define PERM_SMALL_Q(a) do { \ - int r; \ - for (r = 0; r < 10; r ++) \ - ROUND_SMALL_Q(a, r); \ - } while (0) - -#else - -/* - * Apparently, unrolling more than that confuses GCC, resulting in - * lower performance, even though L1 cache would be no problem. - */ -#define PERM_SMALL_P(a) do { \ - int r; \ - for (r = 0; r < 10; r += 2) { \ - ROUND_SMALL_P(a, r + 0); \ - ROUND_SMALL_P(a, r + 1); \ - } \ - } while (0) - -#define PERM_SMALL_Q(a) do { \ - int r; \ - for (r = 0; r < 10; r += 2) { \ - ROUND_SMALL_Q(a, r + 0); \ - ROUND_SMALL_Q(a, r + 1); \ - } \ - } while (0) - -#endif - -#define COMPRESS_SMALL do { \ - sph_u64 g[8], m[8]; \ - size_t u; \ - for (u = 0; u < 8; u ++) { \ - m[u] = dec64e_aligned(buf + (u << 3)); \ - g[u] = m[u] ^ H[u]; \ - } \ - PERM_SMALL_P(g); \ - PERM_SMALL_Q(m); \ - for (u = 0; u < 8; u ++) \ - H[u] ^= g[u] ^ m[u]; \ - } while (0) - -#define FINAL_SMALL do { \ - sph_u64 x[8]; \ - size_t u; \ - memcpy(x, H, sizeof x); \ - PERM_SMALL_P(x); \ - for (u = 0; u < 8; u ++) \ - H[u] ^= x[u]; \ - } while (0) - -#define DECL_STATE_BIG \ - sph_u64 H[16]; - -#define READ_STATE_BIG(sc) do { \ - memcpy(H, (sc)->state.wide, sizeof H); \ - } while (0) - -#define WRITE_STATE_BIG(sc) do { \ - memcpy((sc)->state.wide, H, sizeof H); \ - } while (0) - -#if SPH_SMALL_FOOTPRINT_GROESTL - -#define RBTT(d, a, b0, b1, b2, b3, b4, b5, b6, b7) do { \ - t[d] = T0[B64_0(a[b0])] \ - ^ R64(T0[B64_1(a[b1])], 8) \ - ^ R64(T0[B64_2(a[b2])], 16) \ - ^ R64(T0[B64_3(a[b3])], 24) \ - ^ T4[B64_4(a[b4])] \ - ^ R64(T4[B64_5(a[b5])], 8) \ - ^ R64(T4[B64_6(a[b6])], 16) \ - ^ R64(T4[B64_7(a[b7])], 24); \ - } while (0) - -#else - -#define RBTT(d, a, b0, b1, b2, b3, b4, b5, b6, b7) do { \ - t[d] = T0[B64_0(a[b0])] \ - ^ T1[B64_1(a[b1])] \ - ^ T2[B64_2(a[b2])] \ - ^ T3[B64_3(a[b3])] \ - ^ T4[B64_4(a[b4])] \ - ^ T5[B64_5(a[b5])] \ - ^ T6[B64_6(a[b6])] \ - ^ T7[B64_7(a[b7])]; \ - } while (0) - -#endif - -#if SPH_SMALL_FOOTPRINT_GROESTL - -#define ROUND_BIG_P(a, r) do { \ - sph_u64 t[16]; \ - size_t u; \ - a[0x0] ^= PC64(0x00, r); \ - a[0x1] ^= PC64(0x10, r); \ - a[0x2] ^= PC64(0x20, r); \ - a[0x3] ^= PC64(0x30, r); \ - a[0x4] ^= PC64(0x40, r); \ - a[0x5] ^= PC64(0x50, r); \ - a[0x6] ^= PC64(0x60, r); \ - a[0x7] ^= PC64(0x70, r); \ - a[0x8] ^= PC64(0x80, r); \ - a[0x9] ^= PC64(0x90, r); \ - a[0xA] ^= PC64(0xA0, r); \ - a[0xB] ^= PC64(0xB0, r); \ - a[0xC] ^= PC64(0xC0, r); \ - a[0xD] ^= PC64(0xD0, r); \ - a[0xE] ^= PC64(0xE0, r); \ - a[0xF] ^= PC64(0xF0, r); \ - for (u = 0; u < 16; u += 4) { \ - RBTT(u + 0, a, u + 0, (u + 1) & 0xF, \ - (u + 2) & 0xF, (u + 3) & 0xF, (u + 4) & 0xF, \ - (u + 5) & 0xF, (u + 6) & 0xF, (u + 11) & 0xF); \ - RBTT(u + 1, a, u + 1, (u + 2) & 0xF, \ - (u + 3) & 0xF, (u + 4) & 0xF, (u + 5) & 0xF, \ - (u + 6) & 0xF, (u + 7) & 0xF, (u + 12) & 0xF); \ - RBTT(u + 2, a, u + 2, (u + 3) & 0xF, \ - (u + 4) & 0xF, (u + 5) & 0xF, (u + 6) & 0xF, \ - (u + 7) & 0xF, (u + 8) & 0xF, (u + 13) & 0xF); \ - RBTT(u + 3, a, u + 3, (u + 4) & 0xF, \ - (u + 5) & 0xF, (u + 6) & 0xF, (u + 7) & 0xF, \ - (u + 8) & 0xF, (u + 9) & 0xF, (u + 14) & 0xF); \ - } \ - memcpy(a, t, sizeof t); \ - } while (0) - -#define ROUND_BIG_Q(a, r) do { \ - sph_u64 t[16]; \ - size_t u; \ - a[0x0] ^= QC64(0x00, r); \ - a[0x1] ^= QC64(0x10, r); \ - a[0x2] ^= QC64(0x20, r); \ - a[0x3] ^= QC64(0x30, r); \ - a[0x4] ^= QC64(0x40, r); \ - a[0x5] ^= QC64(0x50, r); \ - a[0x6] ^= QC64(0x60, r); \ - a[0x7] ^= QC64(0x70, r); \ - a[0x8] ^= QC64(0x80, r); \ - a[0x9] ^= QC64(0x90, r); \ - a[0xA] ^= QC64(0xA0, r); \ - a[0xB] ^= QC64(0xB0, r); \ - a[0xC] ^= QC64(0xC0, r); \ - a[0xD] ^= QC64(0xD0, r); \ - a[0xE] ^= QC64(0xE0, r); \ - a[0xF] ^= QC64(0xF0, r); \ - for (u = 0; u < 16; u += 4) { \ - RBTT(u + 0, a, (u + 1) & 0xF, (u + 3) & 0xF, \ - (u + 5) & 0xF, (u + 11) & 0xF, (u + 0) & 0xF, \ - (u + 2) & 0xF, (u + 4) & 0xF, (u + 6) & 0xF); \ - RBTT(u + 1, a, (u + 2) & 0xF, (u + 4) & 0xF, \ - (u + 6) & 0xF, (u + 12) & 0xF, (u + 1) & 0xF, \ - (u + 3) & 0xF, (u + 5) & 0xF, (u + 7) & 0xF); \ - RBTT(u + 2, a, (u + 3) & 0xF, (u + 5) & 0xF, \ - (u + 7) & 0xF, (u + 13) & 0xF, (u + 2) & 0xF, \ - (u + 4) & 0xF, (u + 6) & 0xF, (u + 8) & 0xF); \ - RBTT(u + 3, a, (u + 4) & 0xF, (u + 6) & 0xF, \ - (u + 8) & 0xF, (u + 14) & 0xF, (u + 3) & 0xF, \ - (u + 5) & 0xF, (u + 7) & 0xF, (u + 9) & 0xF); \ - } \ - memcpy(a, t, sizeof t); \ - } while (0) - -#else - -#define ROUND_BIG_P(a, r) do { \ - sph_u64 t[16]; \ - a[0x0] ^= PC64(0x00, r); \ - a[0x1] ^= PC64(0x10, r); \ - a[0x2] ^= PC64(0x20, r); \ - a[0x3] ^= PC64(0x30, r); \ - a[0x4] ^= PC64(0x40, r); \ - a[0x5] ^= PC64(0x50, r); \ - a[0x6] ^= PC64(0x60, r); \ - a[0x7] ^= PC64(0x70, r); \ - a[0x8] ^= PC64(0x80, r); \ - a[0x9] ^= PC64(0x90, r); \ - a[0xA] ^= PC64(0xA0, r); \ - a[0xB] ^= PC64(0xB0, r); \ - a[0xC] ^= PC64(0xC0, r); \ - a[0xD] ^= PC64(0xD0, r); \ - a[0xE] ^= PC64(0xE0, r); \ - a[0xF] ^= PC64(0xF0, r); \ - RBTT(0x0, a, 0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0xB); \ - RBTT(0x1, a, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0xC); \ - RBTT(0x2, a, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0xD); \ - RBTT(0x3, a, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xE); \ - RBTT(0x4, a, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA, 0xF); \ - RBTT(0x5, a, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA, 0xB, 0x0); \ - RBTT(0x6, a, 0x6, 0x7, 0x8, 0x9, 0xA, 0xB, 0xC, 0x1); \ - RBTT(0x7, a, 0x7, 0x8, 0x9, 0xA, 0xB, 0xC, 0xD, 0x2); \ - RBTT(0x8, a, 0x8, 0x9, 0xA, 0xB, 0xC, 0xD, 0xE, 0x3); \ - RBTT(0x9, a, 0x9, 0xA, 0xB, 0xC, 0xD, 0xE, 0xF, 0x4); \ - RBTT(0xA, a, 0xA, 0xB, 0xC, 0xD, 0xE, 0xF, 0x0, 0x5); \ - RBTT(0xB, a, 0xB, 0xC, 0xD, 0xE, 0xF, 0x0, 0x1, 0x6); \ - RBTT(0xC, a, 0xC, 0xD, 0xE, 0xF, 0x0, 0x1, 0x2, 0x7); \ - RBTT(0xD, a, 0xD, 0xE, 0xF, 0x0, 0x1, 0x2, 0x3, 0x8); \ - RBTT(0xE, a, 0xE, 0xF, 0x0, 0x1, 0x2, 0x3, 0x4, 0x9); \ - RBTT(0xF, a, 0xF, 0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0xA); \ - a[0x0] = t[0x0]; \ - a[0x1] = t[0x1]; \ - a[0x2] = t[0x2]; \ - a[0x3] = t[0x3]; \ - a[0x4] = t[0x4]; \ - a[0x5] = t[0x5]; \ - a[0x6] = t[0x6]; \ - a[0x7] = t[0x7]; \ - a[0x8] = t[0x8]; \ - a[0x9] = t[0x9]; \ - a[0xA] = t[0xA]; \ - a[0xB] = t[0xB]; \ - a[0xC] = t[0xC]; \ - a[0xD] = t[0xD]; \ - a[0xE] = t[0xE]; \ - a[0xF] = t[0xF]; \ - } while (0) - -#define ROUND_BIG_Q(a, r) do { \ - sph_u64 t[16]; \ - a[0x0] ^= QC64(0x00, r); \ - a[0x1] ^= QC64(0x10, r); \ - a[0x2] ^= QC64(0x20, r); \ - a[0x3] ^= QC64(0x30, r); \ - a[0x4] ^= QC64(0x40, r); \ - a[0x5] ^= QC64(0x50, r); \ - a[0x6] ^= QC64(0x60, r); \ - a[0x7] ^= QC64(0x70, r); \ - a[0x8] ^= QC64(0x80, r); \ - a[0x9] ^= QC64(0x90, r); \ - a[0xA] ^= QC64(0xA0, r); \ - a[0xB] ^= QC64(0xB0, r); \ - a[0xC] ^= QC64(0xC0, r); \ - a[0xD] ^= QC64(0xD0, r); \ - a[0xE] ^= QC64(0xE0, r); \ - a[0xF] ^= QC64(0xF0, r); \ - RBTT(0x0, a, 0x1, 0x3, 0x5, 0xB, 0x0, 0x2, 0x4, 0x6); \ - RBTT(0x1, a, 0x2, 0x4, 0x6, 0xC, 0x1, 0x3, 0x5, 0x7); \ - RBTT(0x2, a, 0x3, 0x5, 0x7, 0xD, 0x2, 0x4, 0x6, 0x8); \ - RBTT(0x3, a, 0x4, 0x6, 0x8, 0xE, 0x3, 0x5, 0x7, 0x9); \ - RBTT(0x4, a, 0x5, 0x7, 0x9, 0xF, 0x4, 0x6, 0x8, 0xA); \ - RBTT(0x5, a, 0x6, 0x8, 0xA, 0x0, 0x5, 0x7, 0x9, 0xB); \ - RBTT(0x6, a, 0x7, 0x9, 0xB, 0x1, 0x6, 0x8, 0xA, 0xC); \ - RBTT(0x7, a, 0x8, 0xA, 0xC, 0x2, 0x7, 0x9, 0xB, 0xD); \ - RBTT(0x8, a, 0x9, 0xB, 0xD, 0x3, 0x8, 0xA, 0xC, 0xE); \ - RBTT(0x9, a, 0xA, 0xC, 0xE, 0x4, 0x9, 0xB, 0xD, 0xF); \ - RBTT(0xA, a, 0xB, 0xD, 0xF, 0x5, 0xA, 0xC, 0xE, 0x0); \ - RBTT(0xB, a, 0xC, 0xE, 0x0, 0x6, 0xB, 0xD, 0xF, 0x1); \ - RBTT(0xC, a, 0xD, 0xF, 0x1, 0x7, 0xC, 0xE, 0x0, 0x2); \ - RBTT(0xD, a, 0xE, 0x0, 0x2, 0x8, 0xD, 0xF, 0x1, 0x3); \ - RBTT(0xE, a, 0xF, 0x1, 0x3, 0x9, 0xE, 0x0, 0x2, 0x4); \ - RBTT(0xF, a, 0x0, 0x2, 0x4, 0xA, 0xF, 0x1, 0x3, 0x5); \ - a[0x0] = t[0x0]; \ - a[0x1] = t[0x1]; \ - a[0x2] = t[0x2]; \ - a[0x3] = t[0x3]; \ - a[0x4] = t[0x4]; \ - a[0x5] = t[0x5]; \ - a[0x6] = t[0x6]; \ - a[0x7] = t[0x7]; \ - a[0x8] = t[0x8]; \ - a[0x9] = t[0x9]; \ - a[0xA] = t[0xA]; \ - a[0xB] = t[0xB]; \ - a[0xC] = t[0xC]; \ - a[0xD] = t[0xD]; \ - a[0xE] = t[0xE]; \ - a[0xF] = t[0xF]; \ - } while (0) - -#endif - -#define PERM_BIG_P(a) do { \ - int r; \ - for (r = 0; r < 14; r += 2) { \ - ROUND_BIG_P(a, r + 0); \ - ROUND_BIG_P(a, r + 1); \ - } \ - } while (0) - -#define PERM_BIG_Q(a) do { \ - int r; \ - for (r = 0; r < 14; r += 2) { \ - ROUND_BIG_Q(a, r + 0); \ - ROUND_BIG_Q(a, r + 1); \ - } \ - } while (0) - -/* obsolete -#if SPH_SMALL_FOOTPRINT_GROESTL - -#define COMPRESS_BIG do { \ - sph_u64 g[16], m[16], *ya; \ - const sph_u64 *yc; \ - size_t u; \ - int i; \ - for (u = 0; u < 16; u ++) { \ - m[u] = dec64e_aligned(buf + (u << 3)); \ - g[u] = m[u] ^ H[u]; \ - } \ - ya = g; \ - yc = CP; \ - for (i = 0; i < 2; i ++) { \ - PERM_BIG(ya, yc); \ - ya = m; \ - yc = CQ; \ - } \ - for (u = 0; u < 16; u ++) { \ - H[u] ^= g[u] ^ m[u]; \ - } \ - } while (0) - -#else -*/ - -#define COMPRESS_BIG do { \ - sph_u64 g[16], m[16]; \ - size_t u; \ - for (u = 0; u < 16; u ++) { \ - m[u] = dec64e_aligned(buf + (u << 3)); \ - g[u] = m[u] ^ H[u]; \ - } \ - PERM_BIG_P(g); \ - PERM_BIG_Q(m); \ - for (u = 0; u < 16; u ++) { \ - H[u] ^= g[u] ^ m[u]; \ - } \ - } while (0) - -/* obsolete -#endif -*/ - -#define FINAL_BIG do { \ - sph_u64 x[16]; \ - size_t u; \ - memcpy(x, H, sizeof x); \ - PERM_BIG_P(x); \ - for (u = 0; u < 16; u ++) \ - H[u] ^= x[u]; \ - } while (0) - -#else - -static const sph_u32 T0up[] = { - C32e(0xc632f4a5), C32e(0xf86f9784), C32e(0xee5eb099), C32e(0xf67a8c8d), - C32e(0xffe8170d), C32e(0xd60adcbd), C32e(0xde16c8b1), C32e(0x916dfc54), - C32e(0x6090f050), C32e(0x02070503), C32e(0xce2ee0a9), C32e(0x56d1877d), - C32e(0xe7cc2b19), C32e(0xb513a662), C32e(0x4d7c31e6), C32e(0xec59b59a), - C32e(0x8f40cf45), C32e(0x1fa3bc9d), C32e(0x8949c040), C32e(0xfa689287), - C32e(0xefd03f15), C32e(0xb29426eb), C32e(0x8ece40c9), C32e(0xfbe61d0b), - C32e(0x416e2fec), C32e(0xb31aa967), C32e(0x5f431cfd), C32e(0x456025ea), - C32e(0x23f9dabf), C32e(0x535102f7), C32e(0xe445a196), C32e(0x9b76ed5b), - C32e(0x75285dc2), C32e(0xe1c5241c), C32e(0x3dd4e9ae), C32e(0x4cf2be6a), - C32e(0x6c82ee5a), C32e(0x7ebdc341), C32e(0xf5f30602), C32e(0x8352d14f), - C32e(0x688ce45c), C32e(0x515607f4), C32e(0xd18d5c34), C32e(0xf9e11808), - C32e(0xe24cae93), C32e(0xab3e9573), C32e(0x6297f553), C32e(0x2a6b413f), - C32e(0x081c140c), C32e(0x9563f652), C32e(0x46e9af65), C32e(0x9d7fe25e), - C32e(0x30487828), C32e(0x37cff8a1), C32e(0x0a1b110f), C32e(0x2febc4b5), - C32e(0x0e151b09), C32e(0x247e5a36), C32e(0x1badb69b), C32e(0xdf98473d), - C32e(0xcda76a26), C32e(0x4ef5bb69), C32e(0x7f334ccd), C32e(0xea50ba9f), - C32e(0x123f2d1b), C32e(0x1da4b99e), C32e(0x58c49c74), C32e(0x3446722e), - C32e(0x3641772d), C32e(0xdc11cdb2), C32e(0xb49d29ee), C32e(0x5b4d16fb), - C32e(0xa4a501f6), C32e(0x76a1d74d), C32e(0xb714a361), C32e(0x7d3449ce), - C32e(0x52df8d7b), C32e(0xdd9f423e), C32e(0x5ecd9371), C32e(0x13b1a297), - C32e(0xa6a204f5), C32e(0xb901b868), C32e(0x00000000), C32e(0xc1b5742c), - C32e(0x40e0a060), C32e(0xe3c2211f), C32e(0x793a43c8), C32e(0xb69a2ced), - C32e(0xd40dd9be), C32e(0x8d47ca46), C32e(0x671770d9), C32e(0x72afdd4b), - C32e(0x94ed79de), C32e(0x98ff67d4), C32e(0xb09323e8), C32e(0x855bde4a), - C32e(0xbb06bd6b), C32e(0xc5bb7e2a), C32e(0x4f7b34e5), C32e(0xedd73a16), - C32e(0x86d254c5), C32e(0x9af862d7), C32e(0x6699ff55), C32e(0x11b6a794), - C32e(0x8ac04acf), C32e(0xe9d93010), C32e(0x040e0a06), C32e(0xfe669881), - C32e(0xa0ab0bf0), C32e(0x78b4cc44), C32e(0x25f0d5ba), C32e(0x4b753ee3), - C32e(0xa2ac0ef3), C32e(0x5d4419fe), C32e(0x80db5bc0), C32e(0x0580858a), - C32e(0x3fd3ecad), C32e(0x21fedfbc), C32e(0x70a8d848), C32e(0xf1fd0c04), - C32e(0x63197adf), C32e(0x772f58c1), C32e(0xaf309f75), C32e(0x42e7a563), - C32e(0x20705030), C32e(0xe5cb2e1a), C32e(0xfdef120e), C32e(0xbf08b76d), - C32e(0x8155d44c), C32e(0x18243c14), C32e(0x26795f35), C32e(0xc3b2712f), - C32e(0xbe8638e1), C32e(0x35c8fda2), C32e(0x88c74fcc), C32e(0x2e654b39), - C32e(0x936af957), C32e(0x55580df2), C32e(0xfc619d82), C32e(0x7ab3c947), - C32e(0xc827efac), C32e(0xba8832e7), C32e(0x324f7d2b), C32e(0xe642a495), - C32e(0xc03bfba0), C32e(0x19aab398), C32e(0x9ef668d1), C32e(0xa322817f), - C32e(0x44eeaa66), C32e(0x54d6827e), C32e(0x3bdde6ab), C32e(0x0b959e83), - C32e(0x8cc945ca), C32e(0xc7bc7b29), C32e(0x6b056ed3), C32e(0x286c443c), - C32e(0xa72c8b79), C32e(0xbc813de2), C32e(0x1631271d), C32e(0xad379a76), - C32e(0xdb964d3b), C32e(0x649efa56), C32e(0x74a6d24e), C32e(0x1436221e), - C32e(0x92e476db), C32e(0x0c121e0a), C32e(0x48fcb46c), C32e(0xb88f37e4), - C32e(0x9f78e75d), C32e(0xbd0fb26e), C32e(0x43692aef), C32e(0xc435f1a6), - C32e(0x39dae3a8), C32e(0x31c6f7a4), C32e(0xd38a5937), C32e(0xf274868b), - C32e(0xd5835632), C32e(0x8b4ec543), C32e(0x6e85eb59), C32e(0xda18c2b7), - C32e(0x018e8f8c), C32e(0xb11dac64), C32e(0x9cf16dd2), C32e(0x49723be0), - C32e(0xd81fc7b4), C32e(0xacb915fa), C32e(0xf3fa0907), C32e(0xcfa06f25), - C32e(0xca20eaaf), C32e(0xf47d898e), C32e(0x476720e9), C32e(0x10382818), - C32e(0x6f0b64d5), C32e(0xf0738388), C32e(0x4afbb16f), C32e(0x5cca9672), - C32e(0x38546c24), C32e(0x575f08f1), C32e(0x732152c7), C32e(0x9764f351), - C32e(0xcbae6523), C32e(0xa125847c), C32e(0xe857bf9c), C32e(0x3e5d6321), - C32e(0x96ea7cdd), C32e(0x611e7fdc), C32e(0x0d9c9186), C32e(0x0f9b9485), - C32e(0xe04bab90), C32e(0x7cbac642), C32e(0x712657c4), C32e(0xcc29e5aa), - C32e(0x90e373d8), C32e(0x06090f05), C32e(0xf7f40301), C32e(0x1c2a3612), - C32e(0xc23cfea3), C32e(0x6a8be15f), C32e(0xaebe10f9), C32e(0x69026bd0), - C32e(0x17bfa891), C32e(0x9971e858), C32e(0x3a536927), C32e(0x27f7d0b9), - C32e(0xd9914838), C32e(0xebde3513), C32e(0x2be5ceb3), C32e(0x22775533), - C32e(0xd204d6bb), C32e(0xa9399070), C32e(0x07878089), C32e(0x33c1f2a7), - C32e(0x2decc1b6), C32e(0x3c5a6622), C32e(0x15b8ad92), C32e(0xc9a96020), - C32e(0x875cdb49), C32e(0xaab01aff), C32e(0x50d88878), C32e(0xa52b8e7a), - C32e(0x03898a8f), C32e(0x594a13f8), C32e(0x09929b80), C32e(0x1a233917), - C32e(0x651075da), C32e(0xd7845331), C32e(0x84d551c6), C32e(0xd003d3b8), - C32e(0x82dc5ec3), C32e(0x29e2cbb0), C32e(0x5ac39977), C32e(0x1e2d3311), - C32e(0x7b3d46cb), C32e(0xa8b71ffc), C32e(0x6d0c61d6), C32e(0x2c624e3a) -}; - -static const sph_u32 T0dn[] = { - C32e(0xf497a5c6), C32e(0x97eb84f8), C32e(0xb0c799ee), C32e(0x8cf78df6), - C32e(0x17e50dff), C32e(0xdcb7bdd6), C32e(0xc8a7b1de), C32e(0xfc395491), - C32e(0xf0c05060), C32e(0x05040302), C32e(0xe087a9ce), C32e(0x87ac7d56), - C32e(0x2bd519e7), C32e(0xa67162b5), C32e(0x319ae64d), C32e(0xb5c39aec), - C32e(0xcf05458f), C32e(0xbc3e9d1f), C32e(0xc0094089), C32e(0x92ef87fa), - C32e(0x3fc515ef), C32e(0x267febb2), C32e(0x4007c98e), C32e(0x1ded0bfb), - C32e(0x2f82ec41), C32e(0xa97d67b3), C32e(0x1cbefd5f), C32e(0x258aea45), - C32e(0xda46bf23), C32e(0x02a6f753), C32e(0xa1d396e4), C32e(0xed2d5b9b), - C32e(0x5deac275), C32e(0x24d91ce1), C32e(0xe97aae3d), C32e(0xbe986a4c), - C32e(0xeed85a6c), C32e(0xc3fc417e), C32e(0x06f102f5), C32e(0xd11d4f83), - C32e(0xe4d05c68), C32e(0x07a2f451), C32e(0x5cb934d1), C32e(0x18e908f9), - C32e(0xaedf93e2), C32e(0x954d73ab), C32e(0xf5c45362), C32e(0x41543f2a), - C32e(0x14100c08), C32e(0xf6315295), C32e(0xaf8c6546), C32e(0xe2215e9d), - C32e(0x78602830), C32e(0xf86ea137), C32e(0x11140f0a), C32e(0xc45eb52f), - C32e(0x1b1c090e), C32e(0x5a483624), C32e(0xb6369b1b), C32e(0x47a53ddf), - C32e(0x6a8126cd), C32e(0xbb9c694e), C32e(0x4cfecd7f), C32e(0xbacf9fea), - C32e(0x2d241b12), C32e(0xb93a9e1d), C32e(0x9cb07458), C32e(0x72682e34), - C32e(0x776c2d36), C32e(0xcda3b2dc), C32e(0x2973eeb4), C32e(0x16b6fb5b), - C32e(0x0153f6a4), C32e(0xd7ec4d76), C32e(0xa37561b7), C32e(0x49face7d), - C32e(0x8da47b52), C32e(0x42a13edd), C32e(0x93bc715e), C32e(0xa2269713), - C32e(0x0457f5a6), C32e(0xb86968b9), C32e(0x00000000), C32e(0x74992cc1), - C32e(0xa0806040), C32e(0x21dd1fe3), C32e(0x43f2c879), C32e(0x2c77edb6), - C32e(0xd9b3bed4), C32e(0xca01468d), C32e(0x70ced967), C32e(0xdde44b72), - C32e(0x7933de94), C32e(0x672bd498), C32e(0x237be8b0), C32e(0xde114a85), - C32e(0xbd6d6bbb), C32e(0x7e912ac5), C32e(0x349ee54f), C32e(0x3ac116ed), - C32e(0x5417c586), C32e(0x622fd79a), C32e(0xffcc5566), C32e(0xa7229411), - C32e(0x4a0fcf8a), C32e(0x30c910e9), C32e(0x0a080604), C32e(0x98e781fe), - C32e(0x0b5bf0a0), C32e(0xccf04478), C32e(0xd54aba25), C32e(0x3e96e34b), - C32e(0x0e5ff3a2), C32e(0x19bafe5d), C32e(0x5b1bc080), C32e(0x850a8a05), - C32e(0xec7ead3f), C32e(0xdf42bc21), C32e(0xd8e04870), C32e(0x0cf904f1), - C32e(0x7ac6df63), C32e(0x58eec177), C32e(0x9f4575af), C32e(0xa5846342), - C32e(0x50403020), C32e(0x2ed11ae5), C32e(0x12e10efd), C32e(0xb7656dbf), - C32e(0xd4194c81), C32e(0x3c301418), C32e(0x5f4c3526), C32e(0x719d2fc3), - C32e(0x3867e1be), C32e(0xfd6aa235), C32e(0x4f0bcc88), C32e(0x4b5c392e), - C32e(0xf93d5793), C32e(0x0daaf255), C32e(0x9de382fc), C32e(0xc9f4477a), - C32e(0xef8bacc8), C32e(0x326fe7ba), C32e(0x7d642b32), C32e(0xa4d795e6), - C32e(0xfb9ba0c0), C32e(0xb3329819), C32e(0x6827d19e), C32e(0x815d7fa3), - C32e(0xaa886644), C32e(0x82a87e54), C32e(0xe676ab3b), C32e(0x9e16830b), - C32e(0x4503ca8c), C32e(0x7b9529c7), C32e(0x6ed6d36b), C32e(0x44503c28), - C32e(0x8b5579a7), C32e(0x3d63e2bc), C32e(0x272c1d16), C32e(0x9a4176ad), - C32e(0x4dad3bdb), C32e(0xfac85664), C32e(0xd2e84e74), C32e(0x22281e14), - C32e(0x763fdb92), C32e(0x1e180a0c), C32e(0xb4906c48), C32e(0x376be4b8), - C32e(0xe7255d9f), C32e(0xb2616ebd), C32e(0x2a86ef43), C32e(0xf193a6c4), - C32e(0xe372a839), C32e(0xf762a431), C32e(0x59bd37d3), C32e(0x86ff8bf2), - C32e(0x56b132d5), C32e(0xc50d438b), C32e(0xebdc596e), C32e(0xc2afb7da), - C32e(0x8f028c01), C32e(0xac7964b1), C32e(0x6d23d29c), C32e(0x3b92e049), - C32e(0xc7abb4d8), C32e(0x1543faac), C32e(0x09fd07f3), C32e(0x6f8525cf), - C32e(0xea8fafca), C32e(0x89f38ef4), C32e(0x208ee947), C32e(0x28201810), - C32e(0x64ded56f), C32e(0x83fb88f0), C32e(0xb1946f4a), C32e(0x96b8725c), - C32e(0x6c702438), C32e(0x08aef157), C32e(0x52e6c773), C32e(0xf3355197), - C32e(0x658d23cb), C32e(0x84597ca1), C32e(0xbfcb9ce8), C32e(0x637c213e), - C32e(0x7c37dd96), C32e(0x7fc2dc61), C32e(0x911a860d), C32e(0x941e850f), - C32e(0xabdb90e0), C32e(0xc6f8427c), C32e(0x57e2c471), C32e(0xe583aacc), - C32e(0x733bd890), C32e(0x0f0c0506), C32e(0x03f501f7), C32e(0x3638121c), - C32e(0xfe9fa3c2), C32e(0xe1d45f6a), C32e(0x1047f9ae), C32e(0x6bd2d069), - C32e(0xa82e9117), C32e(0xe8295899), C32e(0x6974273a), C32e(0xd04eb927), - C32e(0x48a938d9), C32e(0x35cd13eb), C32e(0xce56b32b), C32e(0x55443322), - C32e(0xd6bfbbd2), C32e(0x904970a9), C32e(0x800e8907), C32e(0xf266a733), - C32e(0xc15ab62d), C32e(0x6678223c), C32e(0xad2a9215), C32e(0x608920c9), - C32e(0xdb154987), C32e(0x1a4fffaa), C32e(0x88a07850), C32e(0x8e517aa5), - C32e(0x8a068f03), C32e(0x13b2f859), C32e(0x9b128009), C32e(0x3934171a), - C32e(0x75cada65), C32e(0x53b531d7), C32e(0x5113c684), C32e(0xd3bbb8d0), - C32e(0x5e1fc382), C32e(0xcb52b029), C32e(0x99b4775a), C32e(0x333c111e), - C32e(0x46f6cb7b), C32e(0x1f4bfca8), C32e(0x61dad66d), C32e(0x4e583a2c) -}; - -static const sph_u32 T1up[] = { - C32e(0xc6c632f4), C32e(0xf8f86f97), C32e(0xeeee5eb0), C32e(0xf6f67a8c), - C32e(0xffffe817), C32e(0xd6d60adc), C32e(0xdede16c8), C32e(0x91916dfc), - C32e(0x606090f0), C32e(0x02020705), C32e(0xcece2ee0), C32e(0x5656d187), - C32e(0xe7e7cc2b), C32e(0xb5b513a6), C32e(0x4d4d7c31), C32e(0xecec59b5), - C32e(0x8f8f40cf), C32e(0x1f1fa3bc), C32e(0x898949c0), C32e(0xfafa6892), - C32e(0xefefd03f), C32e(0xb2b29426), C32e(0x8e8ece40), C32e(0xfbfbe61d), - C32e(0x41416e2f), C32e(0xb3b31aa9), C32e(0x5f5f431c), C32e(0x45456025), - C32e(0x2323f9da), C32e(0x53535102), C32e(0xe4e445a1), C32e(0x9b9b76ed), - C32e(0x7575285d), C32e(0xe1e1c524), C32e(0x3d3dd4e9), C32e(0x4c4cf2be), - C32e(0x6c6c82ee), C32e(0x7e7ebdc3), C32e(0xf5f5f306), C32e(0x838352d1), - C32e(0x68688ce4), C32e(0x51515607), C32e(0xd1d18d5c), C32e(0xf9f9e118), - C32e(0xe2e24cae), C32e(0xabab3e95), C32e(0x626297f5), C32e(0x2a2a6b41), - C32e(0x08081c14), C32e(0x959563f6), C32e(0x4646e9af), C32e(0x9d9d7fe2), - C32e(0x30304878), C32e(0x3737cff8), C32e(0x0a0a1b11), C32e(0x2f2febc4), - C32e(0x0e0e151b), C32e(0x24247e5a), C32e(0x1b1badb6), C32e(0xdfdf9847), - C32e(0xcdcda76a), C32e(0x4e4ef5bb), C32e(0x7f7f334c), C32e(0xeaea50ba), - C32e(0x12123f2d), C32e(0x1d1da4b9), C32e(0x5858c49c), C32e(0x34344672), - C32e(0x36364177), C32e(0xdcdc11cd), C32e(0xb4b49d29), C32e(0x5b5b4d16), - C32e(0xa4a4a501), C32e(0x7676a1d7), C32e(0xb7b714a3), C32e(0x7d7d3449), - C32e(0x5252df8d), C32e(0xdddd9f42), C32e(0x5e5ecd93), C32e(0x1313b1a2), - C32e(0xa6a6a204), C32e(0xb9b901b8), C32e(0x00000000), C32e(0xc1c1b574), - C32e(0x4040e0a0), C32e(0xe3e3c221), C32e(0x79793a43), C32e(0xb6b69a2c), - C32e(0xd4d40dd9), C32e(0x8d8d47ca), C32e(0x67671770), C32e(0x7272afdd), - C32e(0x9494ed79), C32e(0x9898ff67), C32e(0xb0b09323), C32e(0x85855bde), - C32e(0xbbbb06bd), C32e(0xc5c5bb7e), C32e(0x4f4f7b34), C32e(0xededd73a), - C32e(0x8686d254), C32e(0x9a9af862), C32e(0x666699ff), C32e(0x1111b6a7), - C32e(0x8a8ac04a), C32e(0xe9e9d930), C32e(0x04040e0a), C32e(0xfefe6698), - C32e(0xa0a0ab0b), C32e(0x7878b4cc), C32e(0x2525f0d5), C32e(0x4b4b753e), - C32e(0xa2a2ac0e), C32e(0x5d5d4419), C32e(0x8080db5b), C32e(0x05058085), - C32e(0x3f3fd3ec), C32e(0x2121fedf), C32e(0x7070a8d8), C32e(0xf1f1fd0c), - C32e(0x6363197a), C32e(0x77772f58), C32e(0xafaf309f), C32e(0x4242e7a5), - C32e(0x20207050), C32e(0xe5e5cb2e), C32e(0xfdfdef12), C32e(0xbfbf08b7), - C32e(0x818155d4), C32e(0x1818243c), C32e(0x2626795f), C32e(0xc3c3b271), - C32e(0xbebe8638), C32e(0x3535c8fd), C32e(0x8888c74f), C32e(0x2e2e654b), - C32e(0x93936af9), C32e(0x5555580d), C32e(0xfcfc619d), C32e(0x7a7ab3c9), - C32e(0xc8c827ef), C32e(0xbaba8832), C32e(0x32324f7d), C32e(0xe6e642a4), - C32e(0xc0c03bfb), C32e(0x1919aab3), C32e(0x9e9ef668), C32e(0xa3a32281), - C32e(0x4444eeaa), C32e(0x5454d682), C32e(0x3b3bdde6), C32e(0x0b0b959e), - C32e(0x8c8cc945), C32e(0xc7c7bc7b), C32e(0x6b6b056e), C32e(0x28286c44), - C32e(0xa7a72c8b), C32e(0xbcbc813d), C32e(0x16163127), C32e(0xadad379a), - C32e(0xdbdb964d), C32e(0x64649efa), C32e(0x7474a6d2), C32e(0x14143622), - C32e(0x9292e476), C32e(0x0c0c121e), C32e(0x4848fcb4), C32e(0xb8b88f37), - C32e(0x9f9f78e7), C32e(0xbdbd0fb2), C32e(0x4343692a), C32e(0xc4c435f1), - C32e(0x3939dae3), C32e(0x3131c6f7), C32e(0xd3d38a59), C32e(0xf2f27486), - C32e(0xd5d58356), C32e(0x8b8b4ec5), C32e(0x6e6e85eb), C32e(0xdada18c2), - C32e(0x01018e8f), C32e(0xb1b11dac), C32e(0x9c9cf16d), C32e(0x4949723b), - C32e(0xd8d81fc7), C32e(0xacacb915), C32e(0xf3f3fa09), C32e(0xcfcfa06f), - C32e(0xcaca20ea), C32e(0xf4f47d89), C32e(0x47476720), C32e(0x10103828), - C32e(0x6f6f0b64), C32e(0xf0f07383), C32e(0x4a4afbb1), C32e(0x5c5cca96), - C32e(0x3838546c), C32e(0x57575f08), C32e(0x73732152), C32e(0x979764f3), - C32e(0xcbcbae65), C32e(0xa1a12584), C32e(0xe8e857bf), C32e(0x3e3e5d63), - C32e(0x9696ea7c), C32e(0x61611e7f), C32e(0x0d0d9c91), C32e(0x0f0f9b94), - C32e(0xe0e04bab), C32e(0x7c7cbac6), C32e(0x71712657), C32e(0xcccc29e5), - C32e(0x9090e373), C32e(0x0606090f), C32e(0xf7f7f403), C32e(0x1c1c2a36), - C32e(0xc2c23cfe), C32e(0x6a6a8be1), C32e(0xaeaebe10), C32e(0x6969026b), - C32e(0x1717bfa8), C32e(0x999971e8), C32e(0x3a3a5369), C32e(0x2727f7d0), - C32e(0xd9d99148), C32e(0xebebde35), C32e(0x2b2be5ce), C32e(0x22227755), - C32e(0xd2d204d6), C32e(0xa9a93990), C32e(0x07078780), C32e(0x3333c1f2), - C32e(0x2d2decc1), C32e(0x3c3c5a66), C32e(0x1515b8ad), C32e(0xc9c9a960), - C32e(0x87875cdb), C32e(0xaaaab01a), C32e(0x5050d888), C32e(0xa5a52b8e), - C32e(0x0303898a), C32e(0x59594a13), C32e(0x0909929b), C32e(0x1a1a2339), - C32e(0x65651075), C32e(0xd7d78453), C32e(0x8484d551), C32e(0xd0d003d3), - C32e(0x8282dc5e), C32e(0x2929e2cb), C32e(0x5a5ac399), C32e(0x1e1e2d33), - C32e(0x7b7b3d46), C32e(0xa8a8b71f), C32e(0x6d6d0c61), C32e(0x2c2c624e) -}; - -static const sph_u32 T1dn[] = { - C32e(0xa5f497a5), C32e(0x8497eb84), C32e(0x99b0c799), C32e(0x8d8cf78d), - C32e(0x0d17e50d), C32e(0xbddcb7bd), C32e(0xb1c8a7b1), C32e(0x54fc3954), - C32e(0x50f0c050), C32e(0x03050403), C32e(0xa9e087a9), C32e(0x7d87ac7d), - C32e(0x192bd519), C32e(0x62a67162), C32e(0xe6319ae6), C32e(0x9ab5c39a), - C32e(0x45cf0545), C32e(0x9dbc3e9d), C32e(0x40c00940), C32e(0x8792ef87), - C32e(0x153fc515), C32e(0xeb267feb), C32e(0xc94007c9), C32e(0x0b1ded0b), - C32e(0xec2f82ec), C32e(0x67a97d67), C32e(0xfd1cbefd), C32e(0xea258aea), - C32e(0xbfda46bf), C32e(0xf702a6f7), C32e(0x96a1d396), C32e(0x5bed2d5b), - C32e(0xc25deac2), C32e(0x1c24d91c), C32e(0xaee97aae), C32e(0x6abe986a), - C32e(0x5aeed85a), C32e(0x41c3fc41), C32e(0x0206f102), C32e(0x4fd11d4f), - C32e(0x5ce4d05c), C32e(0xf407a2f4), C32e(0x345cb934), C32e(0x0818e908), - C32e(0x93aedf93), C32e(0x73954d73), C32e(0x53f5c453), C32e(0x3f41543f), - C32e(0x0c14100c), C32e(0x52f63152), C32e(0x65af8c65), C32e(0x5ee2215e), - C32e(0x28786028), C32e(0xa1f86ea1), C32e(0x0f11140f), C32e(0xb5c45eb5), - C32e(0x091b1c09), C32e(0x365a4836), C32e(0x9bb6369b), C32e(0x3d47a53d), - C32e(0x266a8126), C32e(0x69bb9c69), C32e(0xcd4cfecd), C32e(0x9fbacf9f), - C32e(0x1b2d241b), C32e(0x9eb93a9e), C32e(0x749cb074), C32e(0x2e72682e), - C32e(0x2d776c2d), C32e(0xb2cda3b2), C32e(0xee2973ee), C32e(0xfb16b6fb), - C32e(0xf60153f6), C32e(0x4dd7ec4d), C32e(0x61a37561), C32e(0xce49face), - C32e(0x7b8da47b), C32e(0x3e42a13e), C32e(0x7193bc71), C32e(0x97a22697), - C32e(0xf50457f5), C32e(0x68b86968), C32e(0x00000000), C32e(0x2c74992c), - C32e(0x60a08060), C32e(0x1f21dd1f), C32e(0xc843f2c8), C32e(0xed2c77ed), - C32e(0xbed9b3be), C32e(0x46ca0146), C32e(0xd970ced9), C32e(0x4bdde44b), - C32e(0xde7933de), C32e(0xd4672bd4), C32e(0xe8237be8), C32e(0x4ade114a), - C32e(0x6bbd6d6b), C32e(0x2a7e912a), C32e(0xe5349ee5), C32e(0x163ac116), - C32e(0xc55417c5), C32e(0xd7622fd7), C32e(0x55ffcc55), C32e(0x94a72294), - C32e(0xcf4a0fcf), C32e(0x1030c910), C32e(0x060a0806), C32e(0x8198e781), - C32e(0xf00b5bf0), C32e(0x44ccf044), C32e(0xbad54aba), C32e(0xe33e96e3), - C32e(0xf30e5ff3), C32e(0xfe19bafe), C32e(0xc05b1bc0), C32e(0x8a850a8a), - C32e(0xadec7ead), C32e(0xbcdf42bc), C32e(0x48d8e048), C32e(0x040cf904), - C32e(0xdf7ac6df), C32e(0xc158eec1), C32e(0x759f4575), C32e(0x63a58463), - C32e(0x30504030), C32e(0x1a2ed11a), C32e(0x0e12e10e), C32e(0x6db7656d), - C32e(0x4cd4194c), C32e(0x143c3014), C32e(0x355f4c35), C32e(0x2f719d2f), - C32e(0xe13867e1), C32e(0xa2fd6aa2), C32e(0xcc4f0bcc), C32e(0x394b5c39), - C32e(0x57f93d57), C32e(0xf20daaf2), C32e(0x829de382), C32e(0x47c9f447), - C32e(0xacef8bac), C32e(0xe7326fe7), C32e(0x2b7d642b), C32e(0x95a4d795), - C32e(0xa0fb9ba0), C32e(0x98b33298), C32e(0xd16827d1), C32e(0x7f815d7f), - C32e(0x66aa8866), C32e(0x7e82a87e), C32e(0xabe676ab), C32e(0x839e1683), - C32e(0xca4503ca), C32e(0x297b9529), C32e(0xd36ed6d3), C32e(0x3c44503c), - C32e(0x798b5579), C32e(0xe23d63e2), C32e(0x1d272c1d), C32e(0x769a4176), - C32e(0x3b4dad3b), C32e(0x56fac856), C32e(0x4ed2e84e), C32e(0x1e22281e), - C32e(0xdb763fdb), C32e(0x0a1e180a), C32e(0x6cb4906c), C32e(0xe4376be4), - C32e(0x5de7255d), C32e(0x6eb2616e), C32e(0xef2a86ef), C32e(0xa6f193a6), - C32e(0xa8e372a8), C32e(0xa4f762a4), C32e(0x3759bd37), C32e(0x8b86ff8b), - C32e(0x3256b132), C32e(0x43c50d43), C32e(0x59ebdc59), C32e(0xb7c2afb7), - C32e(0x8c8f028c), C32e(0x64ac7964), C32e(0xd26d23d2), C32e(0xe03b92e0), - C32e(0xb4c7abb4), C32e(0xfa1543fa), C32e(0x0709fd07), C32e(0x256f8525), - C32e(0xafea8faf), C32e(0x8e89f38e), C32e(0xe9208ee9), C32e(0x18282018), - C32e(0xd564ded5), C32e(0x8883fb88), C32e(0x6fb1946f), C32e(0x7296b872), - C32e(0x246c7024), C32e(0xf108aef1), C32e(0xc752e6c7), C32e(0x51f33551), - C32e(0x23658d23), C32e(0x7c84597c), C32e(0x9cbfcb9c), C32e(0x21637c21), - C32e(0xdd7c37dd), C32e(0xdc7fc2dc), C32e(0x86911a86), C32e(0x85941e85), - C32e(0x90abdb90), C32e(0x42c6f842), C32e(0xc457e2c4), C32e(0xaae583aa), - C32e(0xd8733bd8), C32e(0x050f0c05), C32e(0x0103f501), C32e(0x12363812), - C32e(0xa3fe9fa3), C32e(0x5fe1d45f), C32e(0xf91047f9), C32e(0xd06bd2d0), - C32e(0x91a82e91), C32e(0x58e82958), C32e(0x27697427), C32e(0xb9d04eb9), - C32e(0x3848a938), C32e(0x1335cd13), C32e(0xb3ce56b3), C32e(0x33554433), - C32e(0xbbd6bfbb), C32e(0x70904970), C32e(0x89800e89), C32e(0xa7f266a7), - C32e(0xb6c15ab6), C32e(0x22667822), C32e(0x92ad2a92), C32e(0x20608920), - C32e(0x49db1549), C32e(0xff1a4fff), C32e(0x7888a078), C32e(0x7a8e517a), - C32e(0x8f8a068f), C32e(0xf813b2f8), C32e(0x809b1280), C32e(0x17393417), - C32e(0xda75cada), C32e(0x3153b531), C32e(0xc65113c6), C32e(0xb8d3bbb8), - C32e(0xc35e1fc3), C32e(0xb0cb52b0), C32e(0x7799b477), C32e(0x11333c11), - C32e(0xcb46f6cb), C32e(0xfc1f4bfc), C32e(0xd661dad6), C32e(0x3a4e583a) -}; - -static const sph_u32 T2up[] = { - C32e(0xa5c6c632), C32e(0x84f8f86f), C32e(0x99eeee5e), C32e(0x8df6f67a), - C32e(0x0dffffe8), C32e(0xbdd6d60a), C32e(0xb1dede16), C32e(0x5491916d), - C32e(0x50606090), C32e(0x03020207), C32e(0xa9cece2e), C32e(0x7d5656d1), - C32e(0x19e7e7cc), C32e(0x62b5b513), C32e(0xe64d4d7c), C32e(0x9aecec59), - C32e(0x458f8f40), C32e(0x9d1f1fa3), C32e(0x40898949), C32e(0x87fafa68), - C32e(0x15efefd0), C32e(0xebb2b294), C32e(0xc98e8ece), C32e(0x0bfbfbe6), - C32e(0xec41416e), C32e(0x67b3b31a), C32e(0xfd5f5f43), C32e(0xea454560), - C32e(0xbf2323f9), C32e(0xf7535351), C32e(0x96e4e445), C32e(0x5b9b9b76), - C32e(0xc2757528), C32e(0x1ce1e1c5), C32e(0xae3d3dd4), C32e(0x6a4c4cf2), - C32e(0x5a6c6c82), C32e(0x417e7ebd), C32e(0x02f5f5f3), C32e(0x4f838352), - C32e(0x5c68688c), C32e(0xf4515156), C32e(0x34d1d18d), C32e(0x08f9f9e1), - C32e(0x93e2e24c), C32e(0x73abab3e), C32e(0x53626297), C32e(0x3f2a2a6b), - C32e(0x0c08081c), C32e(0x52959563), C32e(0x654646e9), C32e(0x5e9d9d7f), - C32e(0x28303048), C32e(0xa13737cf), C32e(0x0f0a0a1b), C32e(0xb52f2feb), - C32e(0x090e0e15), C32e(0x3624247e), C32e(0x9b1b1bad), C32e(0x3ddfdf98), - C32e(0x26cdcda7), C32e(0x694e4ef5), C32e(0xcd7f7f33), C32e(0x9feaea50), - C32e(0x1b12123f), C32e(0x9e1d1da4), C32e(0x745858c4), C32e(0x2e343446), - C32e(0x2d363641), C32e(0xb2dcdc11), C32e(0xeeb4b49d), C32e(0xfb5b5b4d), - C32e(0xf6a4a4a5), C32e(0x4d7676a1), C32e(0x61b7b714), C32e(0xce7d7d34), - C32e(0x7b5252df), C32e(0x3edddd9f), C32e(0x715e5ecd), C32e(0x971313b1), - C32e(0xf5a6a6a2), C32e(0x68b9b901), C32e(0x00000000), C32e(0x2cc1c1b5), - C32e(0x604040e0), C32e(0x1fe3e3c2), C32e(0xc879793a), C32e(0xedb6b69a), - C32e(0xbed4d40d), C32e(0x468d8d47), C32e(0xd9676717), C32e(0x4b7272af), - C32e(0xde9494ed), C32e(0xd49898ff), C32e(0xe8b0b093), C32e(0x4a85855b), - C32e(0x6bbbbb06), C32e(0x2ac5c5bb), C32e(0xe54f4f7b), C32e(0x16ededd7), - C32e(0xc58686d2), C32e(0xd79a9af8), C32e(0x55666699), C32e(0x941111b6), - C32e(0xcf8a8ac0), C32e(0x10e9e9d9), C32e(0x0604040e), C32e(0x81fefe66), - C32e(0xf0a0a0ab), C32e(0x447878b4), C32e(0xba2525f0), C32e(0xe34b4b75), - C32e(0xf3a2a2ac), C32e(0xfe5d5d44), C32e(0xc08080db), C32e(0x8a050580), - C32e(0xad3f3fd3), C32e(0xbc2121fe), C32e(0x487070a8), C32e(0x04f1f1fd), - C32e(0xdf636319), C32e(0xc177772f), C32e(0x75afaf30), C32e(0x634242e7), - C32e(0x30202070), C32e(0x1ae5e5cb), C32e(0x0efdfdef), C32e(0x6dbfbf08), - C32e(0x4c818155), C32e(0x14181824), C32e(0x35262679), C32e(0x2fc3c3b2), - C32e(0xe1bebe86), C32e(0xa23535c8), C32e(0xcc8888c7), C32e(0x392e2e65), - C32e(0x5793936a), C32e(0xf2555558), C32e(0x82fcfc61), C32e(0x477a7ab3), - C32e(0xacc8c827), C32e(0xe7baba88), C32e(0x2b32324f), C32e(0x95e6e642), - C32e(0xa0c0c03b), C32e(0x981919aa), C32e(0xd19e9ef6), C32e(0x7fa3a322), - C32e(0x664444ee), C32e(0x7e5454d6), C32e(0xab3b3bdd), C32e(0x830b0b95), - C32e(0xca8c8cc9), C32e(0x29c7c7bc), C32e(0xd36b6b05), C32e(0x3c28286c), - C32e(0x79a7a72c), C32e(0xe2bcbc81), C32e(0x1d161631), C32e(0x76adad37), - C32e(0x3bdbdb96), C32e(0x5664649e), C32e(0x4e7474a6), C32e(0x1e141436), - C32e(0xdb9292e4), C32e(0x0a0c0c12), C32e(0x6c4848fc), C32e(0xe4b8b88f), - C32e(0x5d9f9f78), C32e(0x6ebdbd0f), C32e(0xef434369), C32e(0xa6c4c435), - C32e(0xa83939da), C32e(0xa43131c6), C32e(0x37d3d38a), C32e(0x8bf2f274), - C32e(0x32d5d583), C32e(0x438b8b4e), C32e(0x596e6e85), C32e(0xb7dada18), - C32e(0x8c01018e), C32e(0x64b1b11d), C32e(0xd29c9cf1), C32e(0xe0494972), - C32e(0xb4d8d81f), C32e(0xfaacacb9), C32e(0x07f3f3fa), C32e(0x25cfcfa0), - C32e(0xafcaca20), C32e(0x8ef4f47d), C32e(0xe9474767), C32e(0x18101038), - C32e(0xd56f6f0b), C32e(0x88f0f073), C32e(0x6f4a4afb), C32e(0x725c5cca), - C32e(0x24383854), C32e(0xf157575f), C32e(0xc7737321), C32e(0x51979764), - C32e(0x23cbcbae), C32e(0x7ca1a125), C32e(0x9ce8e857), C32e(0x213e3e5d), - C32e(0xdd9696ea), C32e(0xdc61611e), C32e(0x860d0d9c), C32e(0x850f0f9b), - C32e(0x90e0e04b), C32e(0x427c7cba), C32e(0xc4717126), C32e(0xaacccc29), - C32e(0xd89090e3), C32e(0x05060609), C32e(0x01f7f7f4), C32e(0x121c1c2a), - C32e(0xa3c2c23c), C32e(0x5f6a6a8b), C32e(0xf9aeaebe), C32e(0xd0696902), - C32e(0x911717bf), C32e(0x58999971), C32e(0x273a3a53), C32e(0xb92727f7), - C32e(0x38d9d991), C32e(0x13ebebde), C32e(0xb32b2be5), C32e(0x33222277), - C32e(0xbbd2d204), C32e(0x70a9a939), C32e(0x89070787), C32e(0xa73333c1), - C32e(0xb62d2dec), C32e(0x223c3c5a), C32e(0x921515b8), C32e(0x20c9c9a9), - C32e(0x4987875c), C32e(0xffaaaab0), C32e(0x785050d8), C32e(0x7aa5a52b), - C32e(0x8f030389), C32e(0xf859594a), C32e(0x80090992), C32e(0x171a1a23), - C32e(0xda656510), C32e(0x31d7d784), C32e(0xc68484d5), C32e(0xb8d0d003), - C32e(0xc38282dc), C32e(0xb02929e2), C32e(0x775a5ac3), C32e(0x111e1e2d), - C32e(0xcb7b7b3d), C32e(0xfca8a8b7), C32e(0xd66d6d0c), C32e(0x3a2c2c62) -}; - -static const sph_u32 T2dn[] = { - C32e(0xf4a5f497), C32e(0x978497eb), C32e(0xb099b0c7), C32e(0x8c8d8cf7), - C32e(0x170d17e5), C32e(0xdcbddcb7), C32e(0xc8b1c8a7), C32e(0xfc54fc39), - C32e(0xf050f0c0), C32e(0x05030504), C32e(0xe0a9e087), C32e(0x877d87ac), - C32e(0x2b192bd5), C32e(0xa662a671), C32e(0x31e6319a), C32e(0xb59ab5c3), - C32e(0xcf45cf05), C32e(0xbc9dbc3e), C32e(0xc040c009), C32e(0x928792ef), - C32e(0x3f153fc5), C32e(0x26eb267f), C32e(0x40c94007), C32e(0x1d0b1ded), - C32e(0x2fec2f82), C32e(0xa967a97d), C32e(0x1cfd1cbe), C32e(0x25ea258a), - C32e(0xdabfda46), C32e(0x02f702a6), C32e(0xa196a1d3), C32e(0xed5bed2d), - C32e(0x5dc25dea), C32e(0x241c24d9), C32e(0xe9aee97a), C32e(0xbe6abe98), - C32e(0xee5aeed8), C32e(0xc341c3fc), C32e(0x060206f1), C32e(0xd14fd11d), - C32e(0xe45ce4d0), C32e(0x07f407a2), C32e(0x5c345cb9), C32e(0x180818e9), - C32e(0xae93aedf), C32e(0x9573954d), C32e(0xf553f5c4), C32e(0x413f4154), - C32e(0x140c1410), C32e(0xf652f631), C32e(0xaf65af8c), C32e(0xe25ee221), - C32e(0x78287860), C32e(0xf8a1f86e), C32e(0x110f1114), C32e(0xc4b5c45e), - C32e(0x1b091b1c), C32e(0x5a365a48), C32e(0xb69bb636), C32e(0x473d47a5), - C32e(0x6a266a81), C32e(0xbb69bb9c), C32e(0x4ccd4cfe), C32e(0xba9fbacf), - C32e(0x2d1b2d24), C32e(0xb99eb93a), C32e(0x9c749cb0), C32e(0x722e7268), - C32e(0x772d776c), C32e(0xcdb2cda3), C32e(0x29ee2973), C32e(0x16fb16b6), - C32e(0x01f60153), C32e(0xd74dd7ec), C32e(0xa361a375), C32e(0x49ce49fa), - C32e(0x8d7b8da4), C32e(0x423e42a1), C32e(0x937193bc), C32e(0xa297a226), - C32e(0x04f50457), C32e(0xb868b869), C32e(0x00000000), C32e(0x742c7499), - C32e(0xa060a080), C32e(0x211f21dd), C32e(0x43c843f2), C32e(0x2ced2c77), - C32e(0xd9bed9b3), C32e(0xca46ca01), C32e(0x70d970ce), C32e(0xdd4bdde4), - C32e(0x79de7933), C32e(0x67d4672b), C32e(0x23e8237b), C32e(0xde4ade11), - C32e(0xbd6bbd6d), C32e(0x7e2a7e91), C32e(0x34e5349e), C32e(0x3a163ac1), - C32e(0x54c55417), C32e(0x62d7622f), C32e(0xff55ffcc), C32e(0xa794a722), - C32e(0x4acf4a0f), C32e(0x301030c9), C32e(0x0a060a08), C32e(0x988198e7), - C32e(0x0bf00b5b), C32e(0xcc44ccf0), C32e(0xd5bad54a), C32e(0x3ee33e96), - C32e(0x0ef30e5f), C32e(0x19fe19ba), C32e(0x5bc05b1b), C32e(0x858a850a), - C32e(0xecadec7e), C32e(0xdfbcdf42), C32e(0xd848d8e0), C32e(0x0c040cf9), - C32e(0x7adf7ac6), C32e(0x58c158ee), C32e(0x9f759f45), C32e(0xa563a584), - C32e(0x50305040), C32e(0x2e1a2ed1), C32e(0x120e12e1), C32e(0xb76db765), - C32e(0xd44cd419), C32e(0x3c143c30), C32e(0x5f355f4c), C32e(0x712f719d), - C32e(0x38e13867), C32e(0xfda2fd6a), C32e(0x4fcc4f0b), C32e(0x4b394b5c), - C32e(0xf957f93d), C32e(0x0df20daa), C32e(0x9d829de3), C32e(0xc947c9f4), - C32e(0xefacef8b), C32e(0x32e7326f), C32e(0x7d2b7d64), C32e(0xa495a4d7), - C32e(0xfba0fb9b), C32e(0xb398b332), C32e(0x68d16827), C32e(0x817f815d), - C32e(0xaa66aa88), C32e(0x827e82a8), C32e(0xe6abe676), C32e(0x9e839e16), - C32e(0x45ca4503), C32e(0x7b297b95), C32e(0x6ed36ed6), C32e(0x443c4450), - C32e(0x8b798b55), C32e(0x3de23d63), C32e(0x271d272c), C32e(0x9a769a41), - C32e(0x4d3b4dad), C32e(0xfa56fac8), C32e(0xd24ed2e8), C32e(0x221e2228), - C32e(0x76db763f), C32e(0x1e0a1e18), C32e(0xb46cb490), C32e(0x37e4376b), - C32e(0xe75de725), C32e(0xb26eb261), C32e(0x2aef2a86), C32e(0xf1a6f193), - C32e(0xe3a8e372), C32e(0xf7a4f762), C32e(0x593759bd), C32e(0x868b86ff), - C32e(0x563256b1), C32e(0xc543c50d), C32e(0xeb59ebdc), C32e(0xc2b7c2af), - C32e(0x8f8c8f02), C32e(0xac64ac79), C32e(0x6dd26d23), C32e(0x3be03b92), - C32e(0xc7b4c7ab), C32e(0x15fa1543), C32e(0x090709fd), C32e(0x6f256f85), - C32e(0xeaafea8f), C32e(0x898e89f3), C32e(0x20e9208e), C32e(0x28182820), - C32e(0x64d564de), C32e(0x838883fb), C32e(0xb16fb194), C32e(0x967296b8), - C32e(0x6c246c70), C32e(0x08f108ae), C32e(0x52c752e6), C32e(0xf351f335), - C32e(0x6523658d), C32e(0x847c8459), C32e(0xbf9cbfcb), C32e(0x6321637c), - C32e(0x7cdd7c37), C32e(0x7fdc7fc2), C32e(0x9186911a), C32e(0x9485941e), - C32e(0xab90abdb), C32e(0xc642c6f8), C32e(0x57c457e2), C32e(0xe5aae583), - C32e(0x73d8733b), C32e(0x0f050f0c), C32e(0x030103f5), C32e(0x36123638), - C32e(0xfea3fe9f), C32e(0xe15fe1d4), C32e(0x10f91047), C32e(0x6bd06bd2), - C32e(0xa891a82e), C32e(0xe858e829), C32e(0x69276974), C32e(0xd0b9d04e), - C32e(0x483848a9), C32e(0x351335cd), C32e(0xceb3ce56), C32e(0x55335544), - C32e(0xd6bbd6bf), C32e(0x90709049), C32e(0x8089800e), C32e(0xf2a7f266), - C32e(0xc1b6c15a), C32e(0x66226678), C32e(0xad92ad2a), C32e(0x60206089), - C32e(0xdb49db15), C32e(0x1aff1a4f), C32e(0x887888a0), C32e(0x8e7a8e51), - C32e(0x8a8f8a06), C32e(0x13f813b2), C32e(0x9b809b12), C32e(0x39173934), - C32e(0x75da75ca), C32e(0x533153b5), C32e(0x51c65113), C32e(0xd3b8d3bb), - C32e(0x5ec35e1f), C32e(0xcbb0cb52), C32e(0x997799b4), C32e(0x3311333c), - C32e(0x46cb46f6), C32e(0x1ffc1f4b), C32e(0x61d661da), C32e(0x4e3a4e58) -}; - -static const sph_u32 T3up[] = { - C32e(0x97a5c6c6), C32e(0xeb84f8f8), C32e(0xc799eeee), C32e(0xf78df6f6), - C32e(0xe50dffff), C32e(0xb7bdd6d6), C32e(0xa7b1dede), C32e(0x39549191), - C32e(0xc0506060), C32e(0x04030202), C32e(0x87a9cece), C32e(0xac7d5656), - C32e(0xd519e7e7), C32e(0x7162b5b5), C32e(0x9ae64d4d), C32e(0xc39aecec), - C32e(0x05458f8f), C32e(0x3e9d1f1f), C32e(0x09408989), C32e(0xef87fafa), - C32e(0xc515efef), C32e(0x7febb2b2), C32e(0x07c98e8e), C32e(0xed0bfbfb), - C32e(0x82ec4141), C32e(0x7d67b3b3), C32e(0xbefd5f5f), C32e(0x8aea4545), - C32e(0x46bf2323), C32e(0xa6f75353), C32e(0xd396e4e4), C32e(0x2d5b9b9b), - C32e(0xeac27575), C32e(0xd91ce1e1), C32e(0x7aae3d3d), C32e(0x986a4c4c), - C32e(0xd85a6c6c), C32e(0xfc417e7e), C32e(0xf102f5f5), C32e(0x1d4f8383), - C32e(0xd05c6868), C32e(0xa2f45151), C32e(0xb934d1d1), C32e(0xe908f9f9), - C32e(0xdf93e2e2), C32e(0x4d73abab), C32e(0xc4536262), C32e(0x543f2a2a), - C32e(0x100c0808), C32e(0x31529595), C32e(0x8c654646), C32e(0x215e9d9d), - C32e(0x60283030), C32e(0x6ea13737), C32e(0x140f0a0a), C32e(0x5eb52f2f), - C32e(0x1c090e0e), C32e(0x48362424), C32e(0x369b1b1b), C32e(0xa53ddfdf), - C32e(0x8126cdcd), C32e(0x9c694e4e), C32e(0xfecd7f7f), C32e(0xcf9feaea), - C32e(0x241b1212), C32e(0x3a9e1d1d), C32e(0xb0745858), C32e(0x682e3434), - C32e(0x6c2d3636), C32e(0xa3b2dcdc), C32e(0x73eeb4b4), C32e(0xb6fb5b5b), - C32e(0x53f6a4a4), C32e(0xec4d7676), C32e(0x7561b7b7), C32e(0xface7d7d), - C32e(0xa47b5252), C32e(0xa13edddd), C32e(0xbc715e5e), C32e(0x26971313), - C32e(0x57f5a6a6), C32e(0x6968b9b9), C32e(0x00000000), C32e(0x992cc1c1), - C32e(0x80604040), C32e(0xdd1fe3e3), C32e(0xf2c87979), C32e(0x77edb6b6), - C32e(0xb3bed4d4), C32e(0x01468d8d), C32e(0xced96767), C32e(0xe44b7272), - C32e(0x33de9494), C32e(0x2bd49898), C32e(0x7be8b0b0), C32e(0x114a8585), - C32e(0x6d6bbbbb), C32e(0x912ac5c5), C32e(0x9ee54f4f), C32e(0xc116eded), - C32e(0x17c58686), C32e(0x2fd79a9a), C32e(0xcc556666), C32e(0x22941111), - C32e(0x0fcf8a8a), C32e(0xc910e9e9), C32e(0x08060404), C32e(0xe781fefe), - C32e(0x5bf0a0a0), C32e(0xf0447878), C32e(0x4aba2525), C32e(0x96e34b4b), - C32e(0x5ff3a2a2), C32e(0xbafe5d5d), C32e(0x1bc08080), C32e(0x0a8a0505), - C32e(0x7ead3f3f), C32e(0x42bc2121), C32e(0xe0487070), C32e(0xf904f1f1), - C32e(0xc6df6363), C32e(0xeec17777), C32e(0x4575afaf), C32e(0x84634242), - C32e(0x40302020), C32e(0xd11ae5e5), C32e(0xe10efdfd), C32e(0x656dbfbf), - C32e(0x194c8181), C32e(0x30141818), C32e(0x4c352626), C32e(0x9d2fc3c3), - C32e(0x67e1bebe), C32e(0x6aa23535), C32e(0x0bcc8888), C32e(0x5c392e2e), - C32e(0x3d579393), C32e(0xaaf25555), C32e(0xe382fcfc), C32e(0xf4477a7a), - C32e(0x8bacc8c8), C32e(0x6fe7baba), C32e(0x642b3232), C32e(0xd795e6e6), - C32e(0x9ba0c0c0), C32e(0x32981919), C32e(0x27d19e9e), C32e(0x5d7fa3a3), - C32e(0x88664444), C32e(0xa87e5454), C32e(0x76ab3b3b), C32e(0x16830b0b), - C32e(0x03ca8c8c), C32e(0x9529c7c7), C32e(0xd6d36b6b), C32e(0x503c2828), - C32e(0x5579a7a7), C32e(0x63e2bcbc), C32e(0x2c1d1616), C32e(0x4176adad), - C32e(0xad3bdbdb), C32e(0xc8566464), C32e(0xe84e7474), C32e(0x281e1414), - C32e(0x3fdb9292), C32e(0x180a0c0c), C32e(0x906c4848), C32e(0x6be4b8b8), - C32e(0x255d9f9f), C32e(0x616ebdbd), C32e(0x86ef4343), C32e(0x93a6c4c4), - C32e(0x72a83939), C32e(0x62a43131), C32e(0xbd37d3d3), C32e(0xff8bf2f2), - C32e(0xb132d5d5), C32e(0x0d438b8b), C32e(0xdc596e6e), C32e(0xafb7dada), - C32e(0x028c0101), C32e(0x7964b1b1), C32e(0x23d29c9c), C32e(0x92e04949), - C32e(0xabb4d8d8), C32e(0x43faacac), C32e(0xfd07f3f3), C32e(0x8525cfcf), - C32e(0x8fafcaca), C32e(0xf38ef4f4), C32e(0x8ee94747), C32e(0x20181010), - C32e(0xded56f6f), C32e(0xfb88f0f0), C32e(0x946f4a4a), C32e(0xb8725c5c), - C32e(0x70243838), C32e(0xaef15757), C32e(0xe6c77373), C32e(0x35519797), - C32e(0x8d23cbcb), C32e(0x597ca1a1), C32e(0xcb9ce8e8), C32e(0x7c213e3e), - C32e(0x37dd9696), C32e(0xc2dc6161), C32e(0x1a860d0d), C32e(0x1e850f0f), - C32e(0xdb90e0e0), C32e(0xf8427c7c), C32e(0xe2c47171), C32e(0x83aacccc), - C32e(0x3bd89090), C32e(0x0c050606), C32e(0xf501f7f7), C32e(0x38121c1c), - C32e(0x9fa3c2c2), C32e(0xd45f6a6a), C32e(0x47f9aeae), C32e(0xd2d06969), - C32e(0x2e911717), C32e(0x29589999), C32e(0x74273a3a), C32e(0x4eb92727), - C32e(0xa938d9d9), C32e(0xcd13ebeb), C32e(0x56b32b2b), C32e(0x44332222), - C32e(0xbfbbd2d2), C32e(0x4970a9a9), C32e(0x0e890707), C32e(0x66a73333), - C32e(0x5ab62d2d), C32e(0x78223c3c), C32e(0x2a921515), C32e(0x8920c9c9), - C32e(0x15498787), C32e(0x4fffaaaa), C32e(0xa0785050), C32e(0x517aa5a5), - C32e(0x068f0303), C32e(0xb2f85959), C32e(0x12800909), C32e(0x34171a1a), - C32e(0xcada6565), C32e(0xb531d7d7), C32e(0x13c68484), C32e(0xbbb8d0d0), - C32e(0x1fc38282), C32e(0x52b02929), C32e(0xb4775a5a), C32e(0x3c111e1e), - C32e(0xf6cb7b7b), C32e(0x4bfca8a8), C32e(0xdad66d6d), C32e(0x583a2c2c) -}; - -static const sph_u32 T3dn[] = { - C32e(0x32f4a5f4), C32e(0x6f978497), C32e(0x5eb099b0), C32e(0x7a8c8d8c), - C32e(0xe8170d17), C32e(0x0adcbddc), C32e(0x16c8b1c8), C32e(0x6dfc54fc), - C32e(0x90f050f0), C32e(0x07050305), C32e(0x2ee0a9e0), C32e(0xd1877d87), - C32e(0xcc2b192b), C32e(0x13a662a6), C32e(0x7c31e631), C32e(0x59b59ab5), - C32e(0x40cf45cf), C32e(0xa3bc9dbc), C32e(0x49c040c0), C32e(0x68928792), - C32e(0xd03f153f), C32e(0x9426eb26), C32e(0xce40c940), C32e(0xe61d0b1d), - C32e(0x6e2fec2f), C32e(0x1aa967a9), C32e(0x431cfd1c), C32e(0x6025ea25), - C32e(0xf9dabfda), C32e(0x5102f702), C32e(0x45a196a1), C32e(0x76ed5bed), - C32e(0x285dc25d), C32e(0xc5241c24), C32e(0xd4e9aee9), C32e(0xf2be6abe), - C32e(0x82ee5aee), C32e(0xbdc341c3), C32e(0xf3060206), C32e(0x52d14fd1), - C32e(0x8ce45ce4), C32e(0x5607f407), C32e(0x8d5c345c), C32e(0xe1180818), - C32e(0x4cae93ae), C32e(0x3e957395), C32e(0x97f553f5), C32e(0x6b413f41), - C32e(0x1c140c14), C32e(0x63f652f6), C32e(0xe9af65af), C32e(0x7fe25ee2), - C32e(0x48782878), C32e(0xcff8a1f8), C32e(0x1b110f11), C32e(0xebc4b5c4), - C32e(0x151b091b), C32e(0x7e5a365a), C32e(0xadb69bb6), C32e(0x98473d47), - C32e(0xa76a266a), C32e(0xf5bb69bb), C32e(0x334ccd4c), C32e(0x50ba9fba), - C32e(0x3f2d1b2d), C32e(0xa4b99eb9), C32e(0xc49c749c), C32e(0x46722e72), - C32e(0x41772d77), C32e(0x11cdb2cd), C32e(0x9d29ee29), C32e(0x4d16fb16), - C32e(0xa501f601), C32e(0xa1d74dd7), C32e(0x14a361a3), C32e(0x3449ce49), - C32e(0xdf8d7b8d), C32e(0x9f423e42), C32e(0xcd937193), C32e(0xb1a297a2), - C32e(0xa204f504), C32e(0x01b868b8), C32e(0x00000000), C32e(0xb5742c74), - C32e(0xe0a060a0), C32e(0xc2211f21), C32e(0x3a43c843), C32e(0x9a2ced2c), - C32e(0x0dd9bed9), C32e(0x47ca46ca), C32e(0x1770d970), C32e(0xafdd4bdd), - C32e(0xed79de79), C32e(0xff67d467), C32e(0x9323e823), C32e(0x5bde4ade), - C32e(0x06bd6bbd), C32e(0xbb7e2a7e), C32e(0x7b34e534), C32e(0xd73a163a), - C32e(0xd254c554), C32e(0xf862d762), C32e(0x99ff55ff), C32e(0xb6a794a7), - C32e(0xc04acf4a), C32e(0xd9301030), C32e(0x0e0a060a), C32e(0x66988198), - C32e(0xab0bf00b), C32e(0xb4cc44cc), C32e(0xf0d5bad5), C32e(0x753ee33e), - C32e(0xac0ef30e), C32e(0x4419fe19), C32e(0xdb5bc05b), C32e(0x80858a85), - C32e(0xd3ecadec), C32e(0xfedfbcdf), C32e(0xa8d848d8), C32e(0xfd0c040c), - C32e(0x197adf7a), C32e(0x2f58c158), C32e(0x309f759f), C32e(0xe7a563a5), - C32e(0x70503050), C32e(0xcb2e1a2e), C32e(0xef120e12), C32e(0x08b76db7), - C32e(0x55d44cd4), C32e(0x243c143c), C32e(0x795f355f), C32e(0xb2712f71), - C32e(0x8638e138), C32e(0xc8fda2fd), C32e(0xc74fcc4f), C32e(0x654b394b), - C32e(0x6af957f9), C32e(0x580df20d), C32e(0x619d829d), C32e(0xb3c947c9), - C32e(0x27efacef), C32e(0x8832e732), C32e(0x4f7d2b7d), C32e(0x42a495a4), - C32e(0x3bfba0fb), C32e(0xaab398b3), C32e(0xf668d168), C32e(0x22817f81), - C32e(0xeeaa66aa), C32e(0xd6827e82), C32e(0xdde6abe6), C32e(0x959e839e), - C32e(0xc945ca45), C32e(0xbc7b297b), C32e(0x056ed36e), C32e(0x6c443c44), - C32e(0x2c8b798b), C32e(0x813de23d), C32e(0x31271d27), C32e(0x379a769a), - C32e(0x964d3b4d), C32e(0x9efa56fa), C32e(0xa6d24ed2), C32e(0x36221e22), - C32e(0xe476db76), C32e(0x121e0a1e), C32e(0xfcb46cb4), C32e(0x8f37e437), - C32e(0x78e75de7), C32e(0x0fb26eb2), C32e(0x692aef2a), C32e(0x35f1a6f1), - C32e(0xdae3a8e3), C32e(0xc6f7a4f7), C32e(0x8a593759), C32e(0x74868b86), - C32e(0x83563256), C32e(0x4ec543c5), C32e(0x85eb59eb), C32e(0x18c2b7c2), - C32e(0x8e8f8c8f), C32e(0x1dac64ac), C32e(0xf16dd26d), C32e(0x723be03b), - C32e(0x1fc7b4c7), C32e(0xb915fa15), C32e(0xfa090709), C32e(0xa06f256f), - C32e(0x20eaafea), C32e(0x7d898e89), C32e(0x6720e920), C32e(0x38281828), - C32e(0x0b64d564), C32e(0x73838883), C32e(0xfbb16fb1), C32e(0xca967296), - C32e(0x546c246c), C32e(0x5f08f108), C32e(0x2152c752), C32e(0x64f351f3), - C32e(0xae652365), C32e(0x25847c84), C32e(0x57bf9cbf), C32e(0x5d632163), - C32e(0xea7cdd7c), C32e(0x1e7fdc7f), C32e(0x9c918691), C32e(0x9b948594), - C32e(0x4bab90ab), C32e(0xbac642c6), C32e(0x2657c457), C32e(0x29e5aae5), - C32e(0xe373d873), C32e(0x090f050f), C32e(0xf4030103), C32e(0x2a361236), - C32e(0x3cfea3fe), C32e(0x8be15fe1), C32e(0xbe10f910), C32e(0x026bd06b), - C32e(0xbfa891a8), C32e(0x71e858e8), C32e(0x53692769), C32e(0xf7d0b9d0), - C32e(0x91483848), C32e(0xde351335), C32e(0xe5ceb3ce), C32e(0x77553355), - C32e(0x04d6bbd6), C32e(0x39907090), C32e(0x87808980), C32e(0xc1f2a7f2), - C32e(0xecc1b6c1), C32e(0x5a662266), C32e(0xb8ad92ad), C32e(0xa9602060), - C32e(0x5cdb49db), C32e(0xb01aff1a), C32e(0xd8887888), C32e(0x2b8e7a8e), - C32e(0x898a8f8a), C32e(0x4a13f813), C32e(0x929b809b), C32e(0x23391739), - C32e(0x1075da75), C32e(0x84533153), C32e(0xd551c651), C32e(0x03d3b8d3), - C32e(0xdc5ec35e), C32e(0xe2cbb0cb), C32e(0xc3997799), C32e(0x2d331133), - C32e(0x3d46cb46), C32e(0xb71ffc1f), C32e(0x0c61d661), C32e(0x624e3a4e) -}; - -#define DECL_STATE_SMALL \ - sph_u32 H[16]; - -#define READ_STATE_SMALL(sc) do { \ - memcpy(H, (sc)->state.narrow, sizeof H); \ - } while (0) - -#define WRITE_STATE_SMALL(sc) do { \ - memcpy((sc)->state.narrow, H, sizeof H); \ - } while (0) - -#define XCAT(x, y) XCAT_(x, y) -#define XCAT_(x, y) x ## y - -#define RSTT(d0, d1, a, b0, b1, b2, b3, b4, b5, b6, b7) do { \ - t[d0] = T0up[B32_0(a[b0])] \ - ^ T1up[B32_1(a[b1])] \ - ^ T2up[B32_2(a[b2])] \ - ^ T3up[B32_3(a[b3])] \ - ^ T0dn[B32_0(a[b4])] \ - ^ T1dn[B32_1(a[b5])] \ - ^ T2dn[B32_2(a[b6])] \ - ^ T3dn[B32_3(a[b7])]; \ - t[d1] = T0dn[B32_0(a[b0])] \ - ^ T1dn[B32_1(a[b1])] \ - ^ T2dn[B32_2(a[b2])] \ - ^ T3dn[B32_3(a[b3])] \ - ^ T0up[B32_0(a[b4])] \ - ^ T1up[B32_1(a[b5])] \ - ^ T2up[B32_2(a[b6])] \ - ^ T3up[B32_3(a[b7])]; \ - } while (0) - -#define ROUND_SMALL_P(a, r) do { \ - sph_u32 t[16]; \ - a[0x0] ^= PC32up(0x00, r); \ - a[0x1] ^= PC32dn(0x00, r); \ - a[0x2] ^= PC32up(0x10, r); \ - a[0x3] ^= PC32dn(0x10, r); \ - a[0x4] ^= PC32up(0x20, r); \ - a[0x5] ^= PC32dn(0x20, r); \ - a[0x6] ^= PC32up(0x30, r); \ - a[0x7] ^= PC32dn(0x30, r); \ - a[0x8] ^= PC32up(0x40, r); \ - a[0x9] ^= PC32dn(0x40, r); \ - a[0xA] ^= PC32up(0x50, r); \ - a[0xB] ^= PC32dn(0x50, r); \ - a[0xC] ^= PC32up(0x60, r); \ - a[0xD] ^= PC32dn(0x60, r); \ - a[0xE] ^= PC32up(0x70, r); \ - a[0xF] ^= PC32dn(0x70, r); \ - RSTT(0x0, 0x1, a, 0x0, 0x2, 0x4, 0x6, 0x9, 0xB, 0xD, 0xF); \ - RSTT(0x2, 0x3, a, 0x2, 0x4, 0x6, 0x8, 0xB, 0xD, 0xF, 0x1); \ - RSTT(0x4, 0x5, a, 0x4, 0x6, 0x8, 0xA, 0xD, 0xF, 0x1, 0x3); \ - RSTT(0x6, 0x7, a, 0x6, 0x8, 0xA, 0xC, 0xF, 0x1, 0x3, 0x5); \ - RSTT(0x8, 0x9, a, 0x8, 0xA, 0xC, 0xE, 0x1, 0x3, 0x5, 0x7); \ - RSTT(0xA, 0xB, a, 0xA, 0xC, 0xE, 0x0, 0x3, 0x5, 0x7, 0x9); \ - RSTT(0xC, 0xD, a, 0xC, 0xE, 0x0, 0x2, 0x5, 0x7, 0x9, 0xB); \ - RSTT(0xE, 0xF, a, 0xE, 0x0, 0x2, 0x4, 0x7, 0x9, 0xB, 0xD); \ - memcpy(a, t, sizeof t); \ - } while (0) - -#define ROUND_SMALL_Q(a, r) do { \ - sph_u32 t[16]; \ - a[0x0] ^= QC32up(0x00, r); \ - a[0x1] ^= QC32dn(0x00, r); \ - a[0x2] ^= QC32up(0x10, r); \ - a[0x3] ^= QC32dn(0x10, r); \ - a[0x4] ^= QC32up(0x20, r); \ - a[0x5] ^= QC32dn(0x20, r); \ - a[0x6] ^= QC32up(0x30, r); \ - a[0x7] ^= QC32dn(0x30, r); \ - a[0x8] ^= QC32up(0x40, r); \ - a[0x9] ^= QC32dn(0x40, r); \ - a[0xA] ^= QC32up(0x50, r); \ - a[0xB] ^= QC32dn(0x50, r); \ - a[0xC] ^= QC32up(0x60, r); \ - a[0xD] ^= QC32dn(0x60, r); \ - a[0xE] ^= QC32up(0x70, r); \ - a[0xF] ^= QC32dn(0x70, r); \ - RSTT(0x0, 0x1, a, 0x2, 0x6, 0xA, 0xE, 0x1, 0x5, 0x9, 0xD); \ - RSTT(0x2, 0x3, a, 0x4, 0x8, 0xC, 0x0, 0x3, 0x7, 0xB, 0xF); \ - RSTT(0x4, 0x5, a, 0x6, 0xA, 0xE, 0x2, 0x5, 0x9, 0xD, 0x1); \ - RSTT(0x6, 0x7, a, 0x8, 0xC, 0x0, 0x4, 0x7, 0xB, 0xF, 0x3); \ - RSTT(0x8, 0x9, a, 0xA, 0xE, 0x2, 0x6, 0x9, 0xD, 0x1, 0x5); \ - RSTT(0xA, 0xB, a, 0xC, 0x0, 0x4, 0x8, 0xB, 0xF, 0x3, 0x7); \ - RSTT(0xC, 0xD, a, 0xE, 0x2, 0x6, 0xA, 0xD, 0x1, 0x5, 0x9); \ - RSTT(0xE, 0xF, a, 0x0, 0x4, 0x8, 0xC, 0xF, 0x3, 0x7, 0xB); \ - memcpy(a, t, sizeof t); \ - } while (0) - -#if SPH_SMALL_FOOTPRINT_GROESTL - -#define PERM_SMALL_P(a) do { \ - int r; \ - for (r = 0; r < 10; r ++) \ - ROUND_SMALL_P(a, r); \ - } while (0) - -#define PERM_SMALL_Q(a) do { \ - int r; \ - for (r = 0; r < 10; r ++) \ - ROUND_SMALL_Q(a, r); \ - } while (0) - -#else - -#define PERM_SMALL_P(a) do { \ - int r; \ - for (r = 0; r < 10; r += 2) { \ - ROUND_SMALL_P(a, r + 0); \ - ROUND_SMALL_P(a, r + 1); \ - } \ - } while (0) - -#define PERM_SMALL_Q(a) do { \ - int r; \ - for (r = 0; r < 10; r += 2) { \ - ROUND_SMALL_Q(a, r + 0); \ - ROUND_SMALL_Q(a, r + 1); \ - } \ - } while (0) - -#endif - -#define COMPRESS_SMALL do { \ - sph_u32 g[16], m[16]; \ - size_t u; \ - for (u = 0; u < 16; u ++) { \ - m[u] = dec32e_aligned(buf + (u << 2)); \ - g[u] = m[u] ^ H[u]; \ - } \ - PERM_SMALL_P(g); \ - PERM_SMALL_Q(m); \ - for (u = 0; u < 16; u ++) \ - H[u] ^= g[u] ^ m[u]; \ - } while (0) - -#define FINAL_SMALL do { \ - sph_u32 x[16]; \ - size_t u; \ - memcpy(x, H, sizeof x); \ - PERM_SMALL_P(x); \ - for (u = 0; u < 16; u ++) \ - H[u] ^= x[u]; \ - } while (0) - -#define DECL_STATE_BIG \ - sph_u32 H[32]; - -#define READ_STATE_BIG(sc) do { \ - memcpy(H, (sc)->state.narrow, sizeof H); \ - } while (0) - -#define WRITE_STATE_BIG(sc) do { \ - memcpy((sc)->state.narrow, H, sizeof H); \ - } while (0) - -#if SPH_SMALL_FOOTPRINT_GROESTL - -#define RBTT(d0, d1, a, b0, b1, b2, b3, b4, b5, b6, b7) do { \ - sph_u32 fu2 = T0up[B32_2(a[b2])]; \ - sph_u32 fd2 = T0dn[B32_2(a[b2])]; \ - sph_u32 fu3 = T1up[B32_3(a[b3])]; \ - sph_u32 fd3 = T1dn[B32_3(a[b3])]; \ - sph_u32 fu6 = T0up[B32_2(a[b6])]; \ - sph_u32 fd6 = T0dn[B32_2(a[b6])]; \ - sph_u32 fu7 = T1up[B32_3(a[b7])]; \ - sph_u32 fd7 = T1dn[B32_3(a[b7])]; \ - t[d0] = T0up[B32_0(a[b0])] \ - ^ T1up[B32_1(a[b1])] \ - ^ R32u(fu2, fd2) \ - ^ R32u(fu3, fd3) \ - ^ T0dn[B32_0(a[b4])] \ - ^ T1dn[B32_1(a[b5])] \ - ^ R32d(fu6, fd6) \ - ^ R32d(fu7, fd7); \ - t[d1] = T0dn[B32_0(a[b0])] \ - ^ T1dn[B32_1(a[b1])] \ - ^ R32d(fu2, fd2) \ - ^ R32d(fu3, fd3) \ - ^ T0up[B32_0(a[b4])] \ - ^ T1up[B32_1(a[b5])] \ - ^ R32u(fu6, fd6) \ - ^ R32u(fu7, fd7); \ - } while (0) - -#else - -#define RBTT(d0, d1, a, b0, b1, b2, b3, b4, b5, b6, b7) do { \ - t[d0] = T0up[B32_0(a[b0])] \ - ^ T1up[B32_1(a[b1])] \ - ^ T2up[B32_2(a[b2])] \ - ^ T3up[B32_3(a[b3])] \ - ^ T0dn[B32_0(a[b4])] \ - ^ T1dn[B32_1(a[b5])] \ - ^ T2dn[B32_2(a[b6])] \ - ^ T3dn[B32_3(a[b7])]; \ - t[d1] = T0dn[B32_0(a[b0])] \ - ^ T1dn[B32_1(a[b1])] \ - ^ T2dn[B32_2(a[b2])] \ - ^ T3dn[B32_3(a[b3])] \ - ^ T0up[B32_0(a[b4])] \ - ^ T1up[B32_1(a[b5])] \ - ^ T2up[B32_2(a[b6])] \ - ^ T3up[B32_3(a[b7])]; \ - } while (0) - -#endif - -#if SPH_SMALL_FOOTPRINT_GROESTL - -#define ROUND_BIG_P(a, r) do { \ - sph_u32 t[32]; \ - size_t u; \ - a[0x00] ^= PC32up(0x00, r); \ - a[0x01] ^= PC32dn(0x00, r); \ - a[0x02] ^= PC32up(0x10, r); \ - a[0x03] ^= PC32dn(0x10, r); \ - a[0x04] ^= PC32up(0x20, r); \ - a[0x05] ^= PC32dn(0x20, r); \ - a[0x06] ^= PC32up(0x30, r); \ - a[0x07] ^= PC32dn(0x30, r); \ - a[0x08] ^= PC32up(0x40, r); \ - a[0x09] ^= PC32dn(0x40, r); \ - a[0x0A] ^= PC32up(0x50, r); \ - a[0x0B] ^= PC32dn(0x50, r); \ - a[0x0C] ^= PC32up(0x60, r); \ - a[0x0D] ^= PC32dn(0x60, r); \ - a[0x0E] ^= PC32up(0x70, r); \ - a[0x0F] ^= PC32dn(0x70, r); \ - a[0x10] ^= PC32up(0x80, r); \ - a[0x11] ^= PC32dn(0x80, r); \ - a[0x12] ^= PC32up(0x90, r); \ - a[0x13] ^= PC32dn(0x90, r); \ - a[0x14] ^= PC32up(0xA0, r); \ - a[0x15] ^= PC32dn(0xA0, r); \ - a[0x16] ^= PC32up(0xB0, r); \ - a[0x17] ^= PC32dn(0xB0, r); \ - a[0x18] ^= PC32up(0xC0, r); \ - a[0x19] ^= PC32dn(0xC0, r); \ - a[0x1A] ^= PC32up(0xD0, r); \ - a[0x1B] ^= PC32dn(0xD0, r); \ - a[0x1C] ^= PC32up(0xE0, r); \ - a[0x1D] ^= PC32dn(0xE0, r); \ - a[0x1E] ^= PC32up(0xF0, r); \ - a[0x1F] ^= PC32dn(0xF0, r); \ - for (u = 0; u < 32; u += 8) { \ - RBTT(u + 0x00, (u + 0x01) & 0x1F, a, \ - u + 0x00, (u + 0x02) & 0x1F, \ - (u + 0x04) & 0x1F, (u + 0x06) & 0x1F, \ - (u + 0x09) & 0x1F, (u + 0x0B) & 0x1F, \ - (u + 0x0D) & 0x1F, (u + 0x17) & 0x1F); \ - RBTT(u + 0x02, (u + 0x03) & 0x1F, a, \ - u + 0x02, (u + 0x04) & 0x1F, \ - (u + 0x06) & 0x1F, (u + 0x08) & 0x1F, \ - (u + 0x0B) & 0x1F, (u + 0x0D) & 0x1F, \ - (u + 0x0F) & 0x1F, (u + 0x19) & 0x1F); \ - RBTT(u + 0x04, (u + 0x05) & 0x1F, a, \ - u + 0x04, (u + 0x06) & 0x1F, \ - (u + 0x08) & 0x1F, (u + 0x0A) & 0x1F, \ - (u + 0x0D) & 0x1F, (u + 0x0F) & 0x1F, \ - (u + 0x11) & 0x1F, (u + 0x1B) & 0x1F); \ - RBTT(u + 0x06, (u + 0x07) & 0x1F, a, \ - u + 0x06, (u + 0x08) & 0x1F, \ - (u + 0x0A) & 0x1F, (u + 0x0C) & 0x1F, \ - (u + 0x0F) & 0x1F, (u + 0x11) & 0x1F, \ - (u + 0x13) & 0x1F, (u + 0x1D) & 0x1F); \ - } \ - memcpy(a, t, sizeof t); \ - } while (0) - -#define ROUND_BIG_Q(a, r) do { \ - sph_u32 t[32]; \ - size_t u; \ - a[0x00] ^= QC32up(0x00, r); \ - a[0x01] ^= QC32dn(0x00, r); \ - a[0x02] ^= QC32up(0x10, r); \ - a[0x03] ^= QC32dn(0x10, r); \ - a[0x04] ^= QC32up(0x20, r); \ - a[0x05] ^= QC32dn(0x20, r); \ - a[0x06] ^= QC32up(0x30, r); \ - a[0x07] ^= QC32dn(0x30, r); \ - a[0x08] ^= QC32up(0x40, r); \ - a[0x09] ^= QC32dn(0x40, r); \ - a[0x0A] ^= QC32up(0x50, r); \ - a[0x0B] ^= QC32dn(0x50, r); \ - a[0x0C] ^= QC32up(0x60, r); \ - a[0x0D] ^= QC32dn(0x60, r); \ - a[0x0E] ^= QC32up(0x70, r); \ - a[0x0F] ^= QC32dn(0x70, r); \ - a[0x10] ^= QC32up(0x80, r); \ - a[0x11] ^= QC32dn(0x80, r); \ - a[0x12] ^= QC32up(0x90, r); \ - a[0x13] ^= QC32dn(0x90, r); \ - a[0x14] ^= QC32up(0xA0, r); \ - a[0x15] ^= QC32dn(0xA0, r); \ - a[0x16] ^= QC32up(0xB0, r); \ - a[0x17] ^= QC32dn(0xB0, r); \ - a[0x18] ^= QC32up(0xC0, r); \ - a[0x19] ^= QC32dn(0xC0, r); \ - a[0x1A] ^= QC32up(0xD0, r); \ - a[0x1B] ^= QC32dn(0xD0, r); \ - a[0x1C] ^= QC32up(0xE0, r); \ - a[0x1D] ^= QC32dn(0xE0, r); \ - a[0x1E] ^= QC32up(0xF0, r); \ - a[0x1F] ^= QC32dn(0xF0, r); \ - for (u = 0; u < 32; u += 8) { \ - RBTT(u + 0x00, (u + 0x01) & 0x1F, a, \ - (u + 0x02) & 0x1F, (u + 0x06) & 0x1F, \ - (u + 0x0A) & 0x1F, (u + 0x16) & 0x1F, \ - (u + 0x01) & 0x1F, (u + 0x05) & 0x1F, \ - (u + 0x09) & 0x1F, (u + 0x0D) & 0x1F); \ - RBTT(u + 0x02, (u + 0x03) & 0x1F, a, \ - (u + 0x04) & 0x1F, (u + 0x08) & 0x1F, \ - (u + 0x0C) & 0x1F, (u + 0x18) & 0x1F, \ - (u + 0x03) & 0x1F, (u + 0x07) & 0x1F, \ - (u + 0x0B) & 0x1F, (u + 0x0F) & 0x1F); \ - RBTT(u + 0x04, (u + 0x05) & 0x1F, a, \ - (u + 0x06) & 0x1F, (u + 0x0A) & 0x1F, \ - (u + 0x0E) & 0x1F, (u + 0x1A) & 0x1F, \ - (u + 0x05) & 0x1F, (u + 0x09) & 0x1F, \ - (u + 0x0D) & 0x1F, (u + 0x11) & 0x1F); \ - RBTT(u + 0x06, (u + 0x07) & 0x1F, a, \ - (u + 0x08) & 0x1F, (u + 0x0C) & 0x1F, \ - (u + 0x10) & 0x1F, (u + 0x1C) & 0x1F, \ - (u + 0x07) & 0x1F, (u + 0x0B) & 0x1F, \ - (u + 0x0F) & 0x1F, (u + 0x13) & 0x1F); \ - } \ - memcpy(a, t, sizeof t); \ - } while (0) - -#else - -#define ROUND_BIG_P(a, r) do { \ - sph_u32 t[32]; \ - a[0x00] ^= PC32up(0x00, r); \ - a[0x01] ^= PC32dn(0x00, r); \ - a[0x02] ^= PC32up(0x10, r); \ - a[0x03] ^= PC32dn(0x10, r); \ - a[0x04] ^= PC32up(0x20, r); \ - a[0x05] ^= PC32dn(0x20, r); \ - a[0x06] ^= PC32up(0x30, r); \ - a[0x07] ^= PC32dn(0x30, r); \ - a[0x08] ^= PC32up(0x40, r); \ - a[0x09] ^= PC32dn(0x40, r); \ - a[0x0A] ^= PC32up(0x50, r); \ - a[0x0B] ^= PC32dn(0x50, r); \ - a[0x0C] ^= PC32up(0x60, r); \ - a[0x0D] ^= PC32dn(0x60, r); \ - a[0x0E] ^= PC32up(0x70, r); \ - a[0x0F] ^= PC32dn(0x70, r); \ - a[0x10] ^= PC32up(0x80, r); \ - a[0x11] ^= PC32dn(0x80, r); \ - a[0x12] ^= PC32up(0x90, r); \ - a[0x13] ^= PC32dn(0x90, r); \ - a[0x14] ^= PC32up(0xA0, r); \ - a[0x15] ^= PC32dn(0xA0, r); \ - a[0x16] ^= PC32up(0xB0, r); \ - a[0x17] ^= PC32dn(0xB0, r); \ - a[0x18] ^= PC32up(0xC0, r); \ - a[0x19] ^= PC32dn(0xC0, r); \ - a[0x1A] ^= PC32up(0xD0, r); \ - a[0x1B] ^= PC32dn(0xD0, r); \ - a[0x1C] ^= PC32up(0xE0, r); \ - a[0x1D] ^= PC32dn(0xE0, r); \ - a[0x1E] ^= PC32up(0xF0, r); \ - a[0x1F] ^= PC32dn(0xF0, r); \ - RBTT(0x00, 0x01, a, \ - 0x00, 0x02, 0x04, 0x06, 0x09, 0x0B, 0x0D, 0x17); \ - RBTT(0x02, 0x03, a, \ - 0x02, 0x04, 0x06, 0x08, 0x0B, 0x0D, 0x0F, 0x19); \ - RBTT(0x04, 0x05, a, \ - 0x04, 0x06, 0x08, 0x0A, 0x0D, 0x0F, 0x11, 0x1B); \ - RBTT(0x06, 0x07, a, \ - 0x06, 0x08, 0x0A, 0x0C, 0x0F, 0x11, 0x13, 0x1D); \ - RBTT(0x08, 0x09, a, \ - 0x08, 0x0A, 0x0C, 0x0E, 0x11, 0x13, 0x15, 0x1F); \ - RBTT(0x0A, 0x0B, a, \ - 0x0A, 0x0C, 0x0E, 0x10, 0x13, 0x15, 0x17, 0x01); \ - RBTT(0x0C, 0x0D, a, \ - 0x0C, 0x0E, 0x10, 0x12, 0x15, 0x17, 0x19, 0x03); \ - RBTT(0x0E, 0x0F, a, \ - 0x0E, 0x10, 0x12, 0x14, 0x17, 0x19, 0x1B, 0x05); \ - RBTT(0x10, 0x11, a, \ - 0x10, 0x12, 0x14, 0x16, 0x19, 0x1B, 0x1D, 0x07); \ - RBTT(0x12, 0x13, a, \ - 0x12, 0x14, 0x16, 0x18, 0x1B, 0x1D, 0x1F, 0x09); \ - RBTT(0x14, 0x15, a, \ - 0x14, 0x16, 0x18, 0x1A, 0x1D, 0x1F, 0x01, 0x0B); \ - RBTT(0x16, 0x17, a, \ - 0x16, 0x18, 0x1A, 0x1C, 0x1F, 0x01, 0x03, 0x0D); \ - RBTT(0x18, 0x19, a, \ - 0x18, 0x1A, 0x1C, 0x1E, 0x01, 0x03, 0x05, 0x0F); \ - RBTT(0x1A, 0x1B, a, \ - 0x1A, 0x1C, 0x1E, 0x00, 0x03, 0x05, 0x07, 0x11); \ - RBTT(0x1C, 0x1D, a, \ - 0x1C, 0x1E, 0x00, 0x02, 0x05, 0x07, 0x09, 0x13); \ - RBTT(0x1E, 0x1F, a, \ - 0x1E, 0x00, 0x02, 0x04, 0x07, 0x09, 0x0B, 0x15); \ - memcpy(a, t, sizeof t); \ - } while (0) - -#define ROUND_BIG_Q(a, r) do { \ - sph_u32 t[32]; \ - a[0x00] ^= QC32up(0x00, r); \ - a[0x01] ^= QC32dn(0x00, r); \ - a[0x02] ^= QC32up(0x10, r); \ - a[0x03] ^= QC32dn(0x10, r); \ - a[0x04] ^= QC32up(0x20, r); \ - a[0x05] ^= QC32dn(0x20, r); \ - a[0x06] ^= QC32up(0x30, r); \ - a[0x07] ^= QC32dn(0x30, r); \ - a[0x08] ^= QC32up(0x40, r); \ - a[0x09] ^= QC32dn(0x40, r); \ - a[0x0A] ^= QC32up(0x50, r); \ - a[0x0B] ^= QC32dn(0x50, r); \ - a[0x0C] ^= QC32up(0x60, r); \ - a[0x0D] ^= QC32dn(0x60, r); \ - a[0x0E] ^= QC32up(0x70, r); \ - a[0x0F] ^= QC32dn(0x70, r); \ - a[0x10] ^= QC32up(0x80, r); \ - a[0x11] ^= QC32dn(0x80, r); \ - a[0x12] ^= QC32up(0x90, r); \ - a[0x13] ^= QC32dn(0x90, r); \ - a[0x14] ^= QC32up(0xA0, r); \ - a[0x15] ^= QC32dn(0xA0, r); \ - a[0x16] ^= QC32up(0xB0, r); \ - a[0x17] ^= QC32dn(0xB0, r); \ - a[0x18] ^= QC32up(0xC0, r); \ - a[0x19] ^= QC32dn(0xC0, r); \ - a[0x1A] ^= QC32up(0xD0, r); \ - a[0x1B] ^= QC32dn(0xD0, r); \ - a[0x1C] ^= QC32up(0xE0, r); \ - a[0x1D] ^= QC32dn(0xE0, r); \ - a[0x1E] ^= QC32up(0xF0, r); \ - a[0x1F] ^= QC32dn(0xF0, r); \ - RBTT(0x00, 0x01, a, \ - 0x02, 0x06, 0x0A, 0x16, 0x01, 0x05, 0x09, 0x0D); \ - RBTT(0x02, 0x03, a, \ - 0x04, 0x08, 0x0C, 0x18, 0x03, 0x07, 0x0B, 0x0F); \ - RBTT(0x04, 0x05, a, \ - 0x06, 0x0A, 0x0E, 0x1A, 0x05, 0x09, 0x0D, 0x11); \ - RBTT(0x06, 0x07, a, \ - 0x08, 0x0C, 0x10, 0x1C, 0x07, 0x0B, 0x0F, 0x13); \ - RBTT(0x08, 0x09, a, \ - 0x0A, 0x0E, 0x12, 0x1E, 0x09, 0x0D, 0x11, 0x15); \ - RBTT(0x0A, 0x0B, a, \ - 0x0C, 0x10, 0x14, 0x00, 0x0B, 0x0F, 0x13, 0x17); \ - RBTT(0x0C, 0x0D, a, \ - 0x0E, 0x12, 0x16, 0x02, 0x0D, 0x11, 0x15, 0x19); \ - RBTT(0x0E, 0x0F, a, \ - 0x10, 0x14, 0x18, 0x04, 0x0F, 0x13, 0x17, 0x1B); \ - RBTT(0x10, 0x11, a, \ - 0x12, 0x16, 0x1A, 0x06, 0x11, 0x15, 0x19, 0x1D); \ - RBTT(0x12, 0x13, a, \ - 0x14, 0x18, 0x1C, 0x08, 0x13, 0x17, 0x1B, 0x1F); \ - RBTT(0x14, 0x15, a, \ - 0x16, 0x1A, 0x1E, 0x0A, 0x15, 0x19, 0x1D, 0x01); \ - RBTT(0x16, 0x17, a, \ - 0x18, 0x1C, 0x00, 0x0C, 0x17, 0x1B, 0x1F, 0x03); \ - RBTT(0x18, 0x19, a, \ - 0x1A, 0x1E, 0x02, 0x0E, 0x19, 0x1D, 0x01, 0x05); \ - RBTT(0x1A, 0x1B, a, \ - 0x1C, 0x00, 0x04, 0x10, 0x1B, 0x1F, 0x03, 0x07); \ - RBTT(0x1C, 0x1D, a, \ - 0x1E, 0x02, 0x06, 0x12, 0x1D, 0x01, 0x05, 0x09); \ - RBTT(0x1E, 0x1F, a, \ - 0x00, 0x04, 0x08, 0x14, 0x1F, 0x03, 0x07, 0x0B); \ - memcpy(a, t, sizeof t); \ - } while (0) - -#endif - -#if SPH_SMALL_FOOTPRINT_GROESTL - -#define PERM_BIG_P(a) do { \ - int r; \ - for (r = 0; r < 14; r ++) \ - ROUND_BIG_P(a, r); \ - } while (0) - -#define PERM_BIG_Q(a) do { \ - int r; \ - for (r = 0; r < 14; r ++) \ - ROUND_BIG_Q(a, r); \ - } while (0) - -#else - -#define PERM_BIG_P(a) do { \ - int r; \ - for (r = 0; r < 14; r += 2) { \ - ROUND_BIG_P(a, r + 0); \ - ROUND_BIG_P(a, r + 1); \ - } \ - } while (0) - -#define PERM_BIG_Q(a) do { \ - int r; \ - for (r = 0; r < 14; r += 2) { \ - ROUND_BIG_Q(a, r + 0); \ - ROUND_BIG_Q(a, r + 1); \ - } \ - } while (0) - -#endif - -#define COMPRESS_BIG do { \ - sph_u32 g[32], m[32]; \ - size_t u; \ - for (u = 0; u < 32; u ++) { \ - m[u] = dec32e_aligned(buf + (u << 2)); \ - g[u] = m[u] ^ H[u]; \ - } \ - PERM_BIG_P(g); \ - PERM_BIG_Q(m); \ - for (u = 0; u < 32; u ++) \ - H[u] ^= g[u] ^ m[u]; \ - } while (0) - -#define FINAL_BIG do { \ - sph_u32 x[32]; \ - size_t u; \ - memcpy(x, H, sizeof x); \ - PERM_BIG_P(x); \ - for (u = 0; u < 32; u ++) \ - H[u] ^= x[u]; \ - } while (0) - -#endif - -static void -groestl_small_init(sph_groestl_small_context *sc, unsigned out_size) -{ - size_t u; - - sc->ptr = 0; -#if SPH_GROESTL_64 - for (u = 0; u < 7; u ++) - sc->state.wide[u] = 0; -#if USE_LE - sc->state.wide[7] = ((sph_u64)(out_size & 0xFF) << 56) - | ((sph_u64)(out_size & 0xFF00) << 40); -#else - sc->state.wide[7] = (sph_u64)out_size; -#endif -#else - for (u = 0; u < 15; u ++) - sc->state.narrow[u] = 0; -#if USE_LE - sc->state.narrow[15] = ((sph_u32)(out_size & 0xFF) << 24) - | ((sph_u32)(out_size & 0xFF00) << 8); -#else - sc->state.narrow[15] = (sph_u32)out_size; -#endif -#endif -#if SPH_64 - sc->count = 0; -#else - sc->count_high = 0; - sc->count_low = 0; -#endif -} - -static void -groestl_small_core(sph_groestl_small_context *sc, const void *data, size_t len) -{ - unsigned char *buf; - size_t ptr; - DECL_STATE_SMALL - - buf = sc->buf; - ptr = sc->ptr; - if (len < (sizeof sc->buf) - ptr) { - memcpy(buf + ptr, data, len); - ptr += len; - sc->ptr = ptr; - return; - } - - READ_STATE_SMALL(sc); - while (len > 0) { - size_t clen; - - clen = (sizeof sc->buf) - ptr; - if (clen > len) - clen = len; - memcpy(buf + ptr, data, clen); - ptr += clen; - data = (const unsigned char *)data + clen; - len -= clen; - if (ptr == sizeof sc->buf) { - COMPRESS_SMALL; -#if SPH_64 - sc->count ++; -#else - if ((sc->count_low = SPH_T32(sc->count_low + 1)) == 0) - sc->count_high = SPH_T32(sc->count_high + 1); -#endif - ptr = 0; - } - } - WRITE_STATE_SMALL(sc); - sc->ptr = ptr; -} - -static void -groestl_small_close(sph_groestl_small_context *sc, - unsigned ub, unsigned n, void *dst, size_t out_len) -{ - unsigned char *buf; - unsigned char pad[72]; - size_t u, ptr, pad_len; -#if SPH_64 - sph_u64 count; -#else - sph_u32 count_high, count_low; -#endif - unsigned z; - DECL_STATE_SMALL - - buf = sc->buf; - ptr = sc->ptr; - z = 0x80 >> n; - pad[0] = ((ub & -z) | z) & 0xFF; - if (ptr < 56) { - pad_len = 64 - ptr; -#if SPH_64 - count = SPH_T64(sc->count + 1); -#else - count_low = SPH_T32(sc->count_low + 1); - count_high = SPH_T32(sc->count_high); - if (count_low == 0) - count_high = SPH_T32(count_high + 1); -#endif - } else { - pad_len = 128 - ptr; -#if SPH_64 - count = SPH_T64(sc->count + 2); -#else - count_low = SPH_T32(sc->count_low + 2); - count_high = SPH_T32(sc->count_high); - if (count_low <= 1) - count_high = SPH_T32(count_high + 1); -#endif - } - memset(pad + 1, 0, pad_len - 9); -#if SPH_64 - sph_enc64be(pad + pad_len - 8, count); -#else - sph_enc64be(pad + pad_len - 8, count_high); - sph_enc64be(pad + pad_len - 4, count_low); -#endif - groestl_small_core(sc, pad, pad_len); - READ_STATE_SMALL(sc); - FINAL_SMALL; -#if SPH_GROESTL_64 - for (u = 0; u < 4; u ++) - enc64e(pad + (u << 3), H[u + 4]); -#else - for (u = 0; u < 8; u ++) - enc32e(pad + (u << 2), H[u + 8]); -#endif - memcpy(dst, pad + 32 - out_len, out_len); - groestl_small_init(sc, (unsigned)out_len << 3); -} - -static void -groestl_big_init(sph_groestl_big_context *sc, unsigned out_size) -{ - size_t u; - - sc->ptr = 0; -#if SPH_GROESTL_64 - for (u = 0; u < 15; u ++) - sc->state.wide[u] = 0; -#if USE_LE - sc->state.wide[15] = ((sph_u64)(out_size & 0xFF) << 56) - | ((sph_u64)(out_size & 0xFF00) << 40); -#else - sc->state.wide[15] = (sph_u64)out_size; -#endif -#else - for (u = 0; u < 31; u ++) - sc->state.narrow[u] = 0; -#if USE_LE - sc->state.narrow[31] = ((sph_u32)(out_size & 0xFF) << 24) - | ((sph_u32)(out_size & 0xFF00) << 8); -#else - sc->state.narrow[31] = (sph_u32)out_size; -#endif -#endif -#if SPH_64 - sc->count = 0; -#else - sc->count_high = 0; - sc->count_low = 0; -#endif -} - -static void -groestl_big_core(sph_groestl_big_context *sc, const void *data, size_t len) -{ - unsigned char *buf; - size_t ptr; - DECL_STATE_BIG - - buf = sc->buf; - ptr = sc->ptr; - if (len < (sizeof sc->buf) - ptr) { - memcpy(buf + ptr, data, len); - ptr += len; - sc->ptr = ptr; - return; - } - - READ_STATE_BIG(sc); - while (len > 0) { - size_t clen; - - clen = (sizeof sc->buf) - ptr; - if (clen > len) - clen = len; - memcpy(buf + ptr, data, clen); - ptr += clen; - data = (const unsigned char *)data + clen; - len -= clen; - if (ptr == sizeof sc->buf) { - COMPRESS_BIG; -#if SPH_64 - sc->count ++; -#else - if ((sc->count_low = SPH_T32(sc->count_low + 1)) == 0) - sc->count_high = SPH_T32(sc->count_high + 1); -#endif - ptr = 0; - } - } - WRITE_STATE_BIG(sc); - sc->ptr = ptr; -} - -static void -groestl_big_close(sph_groestl_big_context *sc, - unsigned ub, unsigned n, void *dst, size_t out_len) -{ - unsigned char *buf; - unsigned char pad[136]; - size_t ptr, pad_len, u; -#if SPH_64 - sph_u64 count; -#else - sph_u32 count_high, count_low; -#endif - unsigned z; - DECL_STATE_BIG - - buf = sc->buf; - ptr = sc->ptr; - z = 0x80 >> n; - pad[0] = ((ub & -z) | z) & 0xFF; - if (ptr < 120) { - pad_len = 128 - ptr; -#if SPH_64 - count = SPH_T64(sc->count + 1); -#else - count_low = SPH_T32(sc->count_low + 1); - count_high = SPH_T32(sc->count_high); - if (count_low == 0) - count_high = SPH_T32(count_high + 1); -#endif - } else { - pad_len = 256 - ptr; -#if SPH_64 - count = SPH_T64(sc->count + 2); -#else - count_low = SPH_T32(sc->count_low + 2); - count_high = SPH_T32(sc->count_high); - if (count_low <= 1) - count_high = SPH_T32(count_high + 1); -#endif - } - memset(pad + 1, 0, pad_len - 9); -#if SPH_64 - sph_enc64be(pad + pad_len - 8, count); -#else - sph_enc64be(pad + pad_len - 8, count_high); - sph_enc64be(pad + pad_len - 4, count_low); -#endif - groestl_big_core(sc, pad, pad_len); - READ_STATE_BIG(sc); - FINAL_BIG; -#if SPH_GROESTL_64 - for (u = 0; u < 8; u ++) - enc64e(pad + (u << 3), H[u + 8]); -#else - for (u = 0; u < 16; u ++) - enc32e(pad + (u << 2), H[u + 16]); -#endif - memcpy(dst, pad + 64 - out_len, out_len); - groestl_big_init(sc, (unsigned)out_len << 3); -} - -/* see sph_groestl.h */ -void -sph_groestl224_init(void *cc) -{ - groestl_small_init(cc, 224); -} - -/* see sph_groestl.h */ -void -sph_groestl224(void *cc, const void *data, size_t len) -{ - groestl_small_core(cc, data, len); -} - -/* see sph_groestl.h */ -void -sph_groestl224_close(void *cc, void *dst) -{ - groestl_small_close(cc, 0, 0, dst, 28); -} - -/* see sph_groestl.h */ -void -sph_groestl224_addbits_and_close(void *cc, unsigned ub, unsigned n, void *dst) -{ - groestl_small_close(cc, ub, n, dst, 28); -} - -/* see sph_groestl.h */ -void -sph_groestl256_init(void *cc) -{ - groestl_small_init(cc, 256); -} - -/* see sph_groestl.h */ -void -sph_groestl256(void *cc, const void *data, size_t len) -{ - groestl_small_core(cc, data, len); -} - -/* see sph_groestl.h */ -void -sph_groestl256_close(void *cc, void *dst) -{ - groestl_small_close(cc, 0, 0, dst, 32); -} - -/* see sph_groestl.h */ -void -sph_groestl256_addbits_and_close(void *cc, unsigned ub, unsigned n, void *dst) -{ - groestl_small_close(cc, ub, n, dst, 32); -} - -/* see sph_groestl.h */ -void -sph_groestl384_init(void *cc) -{ - groestl_big_init(cc, 384); -} - -/* see sph_groestl.h */ -void -sph_groestl384(void *cc, const void *data, size_t len) -{ - groestl_big_core(cc, data, len); -} - -/* see sph_groestl.h */ -void -sph_groestl384_close(void *cc, void *dst) -{ - groestl_big_close(cc, 0, 0, dst, 48); -} - -/* see sph_groestl.h */ -void -sph_groestl384_addbits_and_close(void *cc, unsigned ub, unsigned n, void *dst) -{ - groestl_big_close(cc, ub, n, dst, 48); -} - -/* see sph_groestl.h */ -void -sph_groestl512_init(void *cc) -{ - groestl_big_init(cc, 512); -} - -/* see sph_groestl.h */ -void -sph_groestl512(void *cc, const void *data, size_t len) -{ - groestl_big_core(cc, data, len); -} - -/* see sph_groestl.h */ -void -sph_groestl512_close(void *cc, void *dst) -{ - groestl_big_close(cc, 0, 0, dst, 64); -} - -/* see sph_groestl.h */ -void -sph_groestl512_addbits_and_close(void *cc, unsigned ub, unsigned n, void *dst) -{ - groestl_big_close(cc, ub, n, dst, 64); -} - -#ifdef __cplusplus -} -#endif diff --git a/src/crypto/skein.c b/src/crypto/skein.c deleted file mode 100644 index 7e47e352211b..000000000000 --- a/src/crypto/skein.c +++ /dev/null @@ -1,1254 +0,0 @@ -/* $Id: skein.c 254 2011-06-07 19:38:58Z tp $ */ -/* - * Skein implementation. - * - * ==========================(LICENSE BEGIN)============================ - * - * Copyright (c) 2007-2010 Projet RNRT SAPHIR - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY - * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, - * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE - * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - * ===========================(LICENSE END)============================= - * - * @author Thomas Pornin - */ - -#include -#include - -#include "sph_skein.h" - -#ifdef __cplusplus -extern "C"{ -#endif - - -#if SPH_SMALL_FOOTPRINT && !defined SPH_SMALL_FOOTPRINT_SKEIN -#define SPH_SMALL_FOOTPRINT_SKEIN 1 -#endif - -#ifdef _MSC_VER -#pragma warning (disable: 4146) -#endif - -#if SPH_64 - -#if 0 -/* obsolete */ -/* - * M5_ ## s ## _ ## i evaluates to s+i mod 5 (0 <= s <= 18, 0 <= i <= 3). - */ - -#define M5_0_0 0 -#define M5_0_1 1 -#define M5_0_2 2 -#define M5_0_3 3 - -#define M5_1_0 1 -#define M5_1_1 2 -#define M5_1_2 3 -#define M5_1_3 4 - -#define M5_2_0 2 -#define M5_2_1 3 -#define M5_2_2 4 -#define M5_2_3 0 - -#define M5_3_0 3 -#define M5_3_1 4 -#define M5_3_2 0 -#define M5_3_3 1 - -#define M5_4_0 4 -#define M5_4_1 0 -#define M5_4_2 1 -#define M5_4_3 2 - -#define M5_5_0 0 -#define M5_5_1 1 -#define M5_5_2 2 -#define M5_5_3 3 - -#define M5_6_0 1 -#define M5_6_1 2 -#define M5_6_2 3 -#define M5_6_3 4 - -#define M5_7_0 2 -#define M5_7_1 3 -#define M5_7_2 4 -#define M5_7_3 0 - -#define M5_8_0 3 -#define M5_8_1 4 -#define M5_8_2 0 -#define M5_8_3 1 - -#define M5_9_0 4 -#define M5_9_1 0 -#define M5_9_2 1 -#define M5_9_3 2 - -#define M5_10_0 0 -#define M5_10_1 1 -#define M5_10_2 2 -#define M5_10_3 3 - -#define M5_11_0 1 -#define M5_11_1 2 -#define M5_11_2 3 -#define M5_11_3 4 - -#define M5_12_0 2 -#define M5_12_1 3 -#define M5_12_2 4 -#define M5_12_3 0 - -#define M5_13_0 3 -#define M5_13_1 4 -#define M5_13_2 0 -#define M5_13_3 1 - -#define M5_14_0 4 -#define M5_14_1 0 -#define M5_14_2 1 -#define M5_14_3 2 - -#define M5_15_0 0 -#define M5_15_1 1 -#define M5_15_2 2 -#define M5_15_3 3 - -#define M5_16_0 1 -#define M5_16_1 2 -#define M5_16_2 3 -#define M5_16_3 4 - -#define M5_17_0 2 -#define M5_17_1 3 -#define M5_17_2 4 -#define M5_17_3 0 - -#define M5_18_0 3 -#define M5_18_1 4 -#define M5_18_2 0 -#define M5_18_3 1 -#endif - -/* - * M9_ ## s ## _ ## i evaluates to s+i mod 9 (0 <= s <= 18, 0 <= i <= 7). - */ - -#define M9_0_0 0 -#define M9_0_1 1 -#define M9_0_2 2 -#define M9_0_3 3 -#define M9_0_4 4 -#define M9_0_5 5 -#define M9_0_6 6 -#define M9_0_7 7 - -#define M9_1_0 1 -#define M9_1_1 2 -#define M9_1_2 3 -#define M9_1_3 4 -#define M9_1_4 5 -#define M9_1_5 6 -#define M9_1_6 7 -#define M9_1_7 8 - -#define M9_2_0 2 -#define M9_2_1 3 -#define M9_2_2 4 -#define M9_2_3 5 -#define M9_2_4 6 -#define M9_2_5 7 -#define M9_2_6 8 -#define M9_2_7 0 - -#define M9_3_0 3 -#define M9_3_1 4 -#define M9_3_2 5 -#define M9_3_3 6 -#define M9_3_4 7 -#define M9_3_5 8 -#define M9_3_6 0 -#define M9_3_7 1 - -#define M9_4_0 4 -#define M9_4_1 5 -#define M9_4_2 6 -#define M9_4_3 7 -#define M9_4_4 8 -#define M9_4_5 0 -#define M9_4_6 1 -#define M9_4_7 2 - -#define M9_5_0 5 -#define M9_5_1 6 -#define M9_5_2 7 -#define M9_5_3 8 -#define M9_5_4 0 -#define M9_5_5 1 -#define M9_5_6 2 -#define M9_5_7 3 - -#define M9_6_0 6 -#define M9_6_1 7 -#define M9_6_2 8 -#define M9_6_3 0 -#define M9_6_4 1 -#define M9_6_5 2 -#define M9_6_6 3 -#define M9_6_7 4 - -#define M9_7_0 7 -#define M9_7_1 8 -#define M9_7_2 0 -#define M9_7_3 1 -#define M9_7_4 2 -#define M9_7_5 3 -#define M9_7_6 4 -#define M9_7_7 5 - -#define M9_8_0 8 -#define M9_8_1 0 -#define M9_8_2 1 -#define M9_8_3 2 -#define M9_8_4 3 -#define M9_8_5 4 -#define M9_8_6 5 -#define M9_8_7 6 - -#define M9_9_0 0 -#define M9_9_1 1 -#define M9_9_2 2 -#define M9_9_3 3 -#define M9_9_4 4 -#define M9_9_5 5 -#define M9_9_6 6 -#define M9_9_7 7 - -#define M9_10_0 1 -#define M9_10_1 2 -#define M9_10_2 3 -#define M9_10_3 4 -#define M9_10_4 5 -#define M9_10_5 6 -#define M9_10_6 7 -#define M9_10_7 8 - -#define M9_11_0 2 -#define M9_11_1 3 -#define M9_11_2 4 -#define M9_11_3 5 -#define M9_11_4 6 -#define M9_11_5 7 -#define M9_11_6 8 -#define M9_11_7 0 - -#define M9_12_0 3 -#define M9_12_1 4 -#define M9_12_2 5 -#define M9_12_3 6 -#define M9_12_4 7 -#define M9_12_5 8 -#define M9_12_6 0 -#define M9_12_7 1 - -#define M9_13_0 4 -#define M9_13_1 5 -#define M9_13_2 6 -#define M9_13_3 7 -#define M9_13_4 8 -#define M9_13_5 0 -#define M9_13_6 1 -#define M9_13_7 2 - -#define M9_14_0 5 -#define M9_14_1 6 -#define M9_14_2 7 -#define M9_14_3 8 -#define M9_14_4 0 -#define M9_14_5 1 -#define M9_14_6 2 -#define M9_14_7 3 - -#define M9_15_0 6 -#define M9_15_1 7 -#define M9_15_2 8 -#define M9_15_3 0 -#define M9_15_4 1 -#define M9_15_5 2 -#define M9_15_6 3 -#define M9_15_7 4 - -#define M9_16_0 7 -#define M9_16_1 8 -#define M9_16_2 0 -#define M9_16_3 1 -#define M9_16_4 2 -#define M9_16_5 3 -#define M9_16_6 4 -#define M9_16_7 5 - -#define M9_17_0 8 -#define M9_17_1 0 -#define M9_17_2 1 -#define M9_17_3 2 -#define M9_17_4 3 -#define M9_17_5 4 -#define M9_17_6 5 -#define M9_17_7 6 - -#define M9_18_0 0 -#define M9_18_1 1 -#define M9_18_2 2 -#define M9_18_3 3 -#define M9_18_4 4 -#define M9_18_5 5 -#define M9_18_6 6 -#define M9_18_7 7 - -/* - * M3_ ## s ## _ ## i evaluates to s+i mod 3 (0 <= s <= 18, 0 <= i <= 1). - */ - -#define M3_0_0 0 -#define M3_0_1 1 -#define M3_1_0 1 -#define M3_1_1 2 -#define M3_2_0 2 -#define M3_2_1 0 -#define M3_3_0 0 -#define M3_3_1 1 -#define M3_4_0 1 -#define M3_4_1 2 -#define M3_5_0 2 -#define M3_5_1 0 -#define M3_6_0 0 -#define M3_6_1 1 -#define M3_7_0 1 -#define M3_7_1 2 -#define M3_8_0 2 -#define M3_8_1 0 -#define M3_9_0 0 -#define M3_9_1 1 -#define M3_10_0 1 -#define M3_10_1 2 -#define M3_11_0 2 -#define M3_11_1 0 -#define M3_12_0 0 -#define M3_12_1 1 -#define M3_13_0 1 -#define M3_13_1 2 -#define M3_14_0 2 -#define M3_14_1 0 -#define M3_15_0 0 -#define M3_15_1 1 -#define M3_16_0 1 -#define M3_16_1 2 -#define M3_17_0 2 -#define M3_17_1 0 -#define M3_18_0 0 -#define M3_18_1 1 - -#define XCAT(x, y) XCAT_(x, y) -#define XCAT_(x, y) x ## y - -#if 0 -/* obsolete */ -#define SKSI(k, s, i) XCAT(k, XCAT(XCAT(XCAT(M5_, s), _), i)) -#define SKST(t, s, v) XCAT(t, XCAT(XCAT(XCAT(M3_, s), _), v)) -#endif - -#define SKBI(k, s, i) XCAT(k, XCAT(XCAT(XCAT(M9_, s), _), i)) -#define SKBT(t, s, v) XCAT(t, XCAT(XCAT(XCAT(M3_, s), _), v)) - -#if 0 -/* obsolete */ -#define TFSMALL_KINIT(k0, k1, k2, k3, k4, t0, t1, t2) do { \ - k4 = (k0 ^ k1) ^ (k2 ^ k3) ^ SPH_C64(0x1BD11BDAA9FC1A22); \ - t2 = t0 ^ t1; \ - } while (0) -#endif - -#define TFBIG_KINIT(k0, k1, k2, k3, k4, k5, k6, k7, k8, t0, t1, t2) do { \ - k8 = ((k0 ^ k1) ^ (k2 ^ k3)) ^ ((k4 ^ k5) ^ (k6 ^ k7)) \ - ^ SPH_C64(0x1BD11BDAA9FC1A22); \ - t2 = t0 ^ t1; \ - } while (0) - -#if 0 -/* obsolete */ -#define TFSMALL_ADDKEY(w0, w1, w2, w3, k, t, s) do { \ - w0 = SPH_T64(w0 + SKSI(k, s, 0)); \ - w1 = SPH_T64(w1 + SKSI(k, s, 1) + SKST(t, s, 0)); \ - w2 = SPH_T64(w2 + SKSI(k, s, 2) + SKST(t, s, 1)); \ - w3 = SPH_T64(w3 + SKSI(k, s, 3) + (sph_u64)s); \ - } while (0) -#endif - -#if SPH_SMALL_FOOTPRINT_SKEIN - -#define TFBIG_ADDKEY(s, tt0, tt1) do { \ - p0 = SPH_T64(p0 + h[s + 0]); \ - p1 = SPH_T64(p1 + h[s + 1]); \ - p2 = SPH_T64(p2 + h[s + 2]); \ - p3 = SPH_T64(p3 + h[s + 3]); \ - p4 = SPH_T64(p4 + h[s + 4]); \ - p5 = SPH_T64(p5 + h[s + 5] + tt0); \ - p6 = SPH_T64(p6 + h[s + 6] + tt1); \ - p7 = SPH_T64(p7 + h[s + 7] + (sph_u64)s); \ - } while (0) - -#else - -#define TFBIG_ADDKEY(w0, w1, w2, w3, w4, w5, w6, w7, k, t, s) do { \ - w0 = SPH_T64(w0 + SKBI(k, s, 0)); \ - w1 = SPH_T64(w1 + SKBI(k, s, 1)); \ - w2 = SPH_T64(w2 + SKBI(k, s, 2)); \ - w3 = SPH_T64(w3 + SKBI(k, s, 3)); \ - w4 = SPH_T64(w4 + SKBI(k, s, 4)); \ - w5 = SPH_T64(w5 + SKBI(k, s, 5) + SKBT(t, s, 0)); \ - w6 = SPH_T64(w6 + SKBI(k, s, 6) + SKBT(t, s, 1)); \ - w7 = SPH_T64(w7 + SKBI(k, s, 7) + (sph_u64)s); \ - } while (0) - -#endif - -#if 0 -/* obsolete */ -#define TFSMALL_MIX(x0, x1, rc) do { \ - x0 = SPH_T64(x0 + x1); \ - x1 = SPH_ROTL64(x1, rc) ^ x0; \ - } while (0) -#endif - -#define TFBIG_MIX(x0, x1, rc) do { \ - x0 = SPH_T64(x0 + x1); \ - x1 = SPH_ROTL64(x1, rc) ^ x0; \ - } while (0) - -#if 0 -/* obsolete */ -#define TFSMALL_MIX4(w0, w1, w2, w3, rc0, rc1) do { \ - TFSMALL_MIX(w0, w1, rc0); \ - TFSMALL_MIX(w2, w3, rc1); \ - } while (0) -#endif - -#define TFBIG_MIX8(w0, w1, w2, w3, w4, w5, w6, w7, rc0, rc1, rc2, rc3) do { \ - TFBIG_MIX(w0, w1, rc0); \ - TFBIG_MIX(w2, w3, rc1); \ - TFBIG_MIX(w4, w5, rc2); \ - TFBIG_MIX(w6, w7, rc3); \ - } while (0) - -#if 0 -/* obsolete */ -#define TFSMALL_4e(s) do { \ - TFSMALL_ADDKEY(p0, p1, p2, p3, h, t, s); \ - TFSMALL_MIX4(p0, p1, p2, p3, 14, 16); \ - TFSMALL_MIX4(p0, p3, p2, p1, 52, 57); \ - TFSMALL_MIX4(p0, p1, p2, p3, 23, 40); \ - TFSMALL_MIX4(p0, p3, p2, p1, 5, 37); \ - } while (0) - -#define TFSMALL_4o(s) do { \ - TFSMALL_ADDKEY(p0, p1, p2, p3, h, t, s); \ - TFSMALL_MIX4(p0, p1, p2, p3, 25, 33); \ - TFSMALL_MIX4(p0, p3, p2, p1, 46, 12); \ - TFSMALL_MIX4(p0, p1, p2, p3, 58, 22); \ - TFSMALL_MIX4(p0, p3, p2, p1, 32, 32); \ - } while (0) -#endif - -#if SPH_SMALL_FOOTPRINT_SKEIN - -#define TFBIG_4e(s) do { \ - TFBIG_ADDKEY(s, t0, t1); \ - TFBIG_MIX8(p0, p1, p2, p3, p4, p5, p6, p7, 46, 36, 19, 37); \ - TFBIG_MIX8(p2, p1, p4, p7, p6, p5, p0, p3, 33, 27, 14, 42); \ - TFBIG_MIX8(p4, p1, p6, p3, p0, p5, p2, p7, 17, 49, 36, 39); \ - TFBIG_MIX8(p6, p1, p0, p7, p2, p5, p4, p3, 44, 9, 54, 56); \ - } while (0) - -#define TFBIG_4o(s) do { \ - TFBIG_ADDKEY(s, t1, t2); \ - TFBIG_MIX8(p0, p1, p2, p3, p4, p5, p6, p7, 39, 30, 34, 24); \ - TFBIG_MIX8(p2, p1, p4, p7, p6, p5, p0, p3, 13, 50, 10, 17); \ - TFBIG_MIX8(p4, p1, p6, p3, p0, p5, p2, p7, 25, 29, 39, 43); \ - TFBIG_MIX8(p6, p1, p0, p7, p2, p5, p4, p3, 8, 35, 56, 22); \ - } while (0) - -#else - -#define TFBIG_4e(s) do { \ - TFBIG_ADDKEY(p0, p1, p2, p3, p4, p5, p6, p7, h, t, s); \ - TFBIG_MIX8(p0, p1, p2, p3, p4, p5, p6, p7, 46, 36, 19, 37); \ - TFBIG_MIX8(p2, p1, p4, p7, p6, p5, p0, p3, 33, 27, 14, 42); \ - TFBIG_MIX8(p4, p1, p6, p3, p0, p5, p2, p7, 17, 49, 36, 39); \ - TFBIG_MIX8(p6, p1, p0, p7, p2, p5, p4, p3, 44, 9, 54, 56); \ - } while (0) - -#define TFBIG_4o(s) do { \ - TFBIG_ADDKEY(p0, p1, p2, p3, p4, p5, p6, p7, h, t, s); \ - TFBIG_MIX8(p0, p1, p2, p3, p4, p5, p6, p7, 39, 30, 34, 24); \ - TFBIG_MIX8(p2, p1, p4, p7, p6, p5, p0, p3, 13, 50, 10, 17); \ - TFBIG_MIX8(p4, p1, p6, p3, p0, p5, p2, p7, 25, 29, 39, 43); \ - TFBIG_MIX8(p6, p1, p0, p7, p2, p5, p4, p3, 8, 35, 56, 22); \ - } while (0) - -#endif - -#if 0 -/* obsolete */ -#define UBI_SMALL(etype, extra) do { \ - sph_u64 h4, t0, t1, t2; \ - sph_u64 m0 = sph_dec64le(buf + 0); \ - sph_u64 m1 = sph_dec64le(buf + 8); \ - sph_u64 m2 = sph_dec64le(buf + 16); \ - sph_u64 m3 = sph_dec64le(buf + 24); \ - sph_u64 p0 = m0; \ - sph_u64 p1 = m1; \ - sph_u64 p2 = m2; \ - sph_u64 p3 = m3; \ - t0 = SPH_T64(bcount << 5) + (sph_u64)(extra); \ - t1 = (bcount >> 59) + ((sph_u64)(etype) << 55); \ - TFSMALL_KINIT(h0, h1, h2, h3, h4, t0, t1, t2); \ - TFSMALL_4e(0); \ - TFSMALL_4o(1); \ - TFSMALL_4e(2); \ - TFSMALL_4o(3); \ - TFSMALL_4e(4); \ - TFSMALL_4o(5); \ - TFSMALL_4e(6); \ - TFSMALL_4o(7); \ - TFSMALL_4e(8); \ - TFSMALL_4o(9); \ - TFSMALL_4e(10); \ - TFSMALL_4o(11); \ - TFSMALL_4e(12); \ - TFSMALL_4o(13); \ - TFSMALL_4e(14); \ - TFSMALL_4o(15); \ - TFSMALL_4e(16); \ - TFSMALL_4o(17); \ - TFSMALL_ADDKEY(p0, p1, p2, p3, h, t, 18); \ - h0 = m0 ^ p0; \ - h1 = m1 ^ p1; \ - h2 = m2 ^ p2; \ - h3 = m3 ^ p3; \ - } while (0) -#endif - -#if SPH_SMALL_FOOTPRINT_SKEIN - -#define UBI_BIG(etype, extra) do { \ - sph_u64 t0, t1, t2; \ - unsigned u; \ - sph_u64 m0 = sph_dec64le_aligned(buf + 0); \ - sph_u64 m1 = sph_dec64le_aligned(buf + 8); \ - sph_u64 m2 = sph_dec64le_aligned(buf + 16); \ - sph_u64 m3 = sph_dec64le_aligned(buf + 24); \ - sph_u64 m4 = sph_dec64le_aligned(buf + 32); \ - sph_u64 m5 = sph_dec64le_aligned(buf + 40); \ - sph_u64 m6 = sph_dec64le_aligned(buf + 48); \ - sph_u64 m7 = sph_dec64le_aligned(buf + 56); \ - sph_u64 p0 = m0; \ - sph_u64 p1 = m1; \ - sph_u64 p2 = m2; \ - sph_u64 p3 = m3; \ - sph_u64 p4 = m4; \ - sph_u64 p5 = m5; \ - sph_u64 p6 = m6; \ - sph_u64 p7 = m7; \ - t0 = SPH_T64(bcount << 6) + (sph_u64)(extra); \ - t1 = (bcount >> 58) + ((sph_u64)(etype) << 55); \ - TFBIG_KINIT(h[0], h[1], h[2], h[3], h[4], h[5], \ - h[6], h[7], h[8], t0, t1, t2); \ - for (u = 0; u <= 15; u += 3) { \ - h[u + 9] = h[u + 0]; \ - h[u + 10] = h[u + 1]; \ - h[u + 11] = h[u + 2]; \ - } \ - for (u = 0; u < 9; u ++) { \ - sph_u64 s = u << 1; \ - sph_u64 tmp; \ - TFBIG_4e(s); \ - TFBIG_4o(s + 1); \ - tmp = t2; \ - t2 = t1; \ - t1 = t0; \ - t0 = tmp; \ - } \ - TFBIG_ADDKEY(18, t0, t1); \ - h[0] = m0 ^ p0; \ - h[1] = m1 ^ p1; \ - h[2] = m2 ^ p2; \ - h[3] = m3 ^ p3; \ - h[4] = m4 ^ p4; \ - h[5] = m5 ^ p5; \ - h[6] = m6 ^ p6; \ - h[7] = m7 ^ p7; \ - } while (0) - -#else - -#define UBI_BIG(etype, extra) do { \ - sph_u64 h8, t0, t1, t2; \ - sph_u64 m0 = sph_dec64le_aligned(buf + 0); \ - sph_u64 m1 = sph_dec64le_aligned(buf + 8); \ - sph_u64 m2 = sph_dec64le_aligned(buf + 16); \ - sph_u64 m3 = sph_dec64le_aligned(buf + 24); \ - sph_u64 m4 = sph_dec64le_aligned(buf + 32); \ - sph_u64 m5 = sph_dec64le_aligned(buf + 40); \ - sph_u64 m6 = sph_dec64le_aligned(buf + 48); \ - sph_u64 m7 = sph_dec64le_aligned(buf + 56); \ - sph_u64 p0 = m0; \ - sph_u64 p1 = m1; \ - sph_u64 p2 = m2; \ - sph_u64 p3 = m3; \ - sph_u64 p4 = m4; \ - sph_u64 p5 = m5; \ - sph_u64 p6 = m6; \ - sph_u64 p7 = m7; \ - t0 = SPH_T64(bcount << 6) + (sph_u64)(extra); \ - t1 = (bcount >> 58) + ((sph_u64)(etype) << 55); \ - TFBIG_KINIT(h0, h1, h2, h3, h4, h5, h6, h7, h8, t0, t1, t2); \ - TFBIG_4e(0); \ - TFBIG_4o(1); \ - TFBIG_4e(2); \ - TFBIG_4o(3); \ - TFBIG_4e(4); \ - TFBIG_4o(5); \ - TFBIG_4e(6); \ - TFBIG_4o(7); \ - TFBIG_4e(8); \ - TFBIG_4o(9); \ - TFBIG_4e(10); \ - TFBIG_4o(11); \ - TFBIG_4e(12); \ - TFBIG_4o(13); \ - TFBIG_4e(14); \ - TFBIG_4o(15); \ - TFBIG_4e(16); \ - TFBIG_4o(17); \ - TFBIG_ADDKEY(p0, p1, p2, p3, p4, p5, p6, p7, h, t, 18); \ - h0 = m0 ^ p0; \ - h1 = m1 ^ p1; \ - h2 = m2 ^ p2; \ - h3 = m3 ^ p3; \ - h4 = m4 ^ p4; \ - h5 = m5 ^ p5; \ - h6 = m6 ^ p6; \ - h7 = m7 ^ p7; \ - } while (0) - -#endif - -#if 0 -/* obsolete */ -#define DECL_STATE_SMALL \ - sph_u64 h0, h1, h2, h3; \ - sph_u64 bcount; - -#define READ_STATE_SMALL(sc) do { \ - h0 = (sc)->h0; \ - h1 = (sc)->h1; \ - h2 = (sc)->h2; \ - h3 = (sc)->h3; \ - bcount = sc->bcount; \ - } while (0) - -#define WRITE_STATE_SMALL(sc) do { \ - (sc)->h0 = h0; \ - (sc)->h1 = h1; \ - (sc)->h2 = h2; \ - (sc)->h3 = h3; \ - sc->bcount = bcount; \ - } while (0) -#endif - -#if SPH_SMALL_FOOTPRINT_SKEIN - -#define DECL_STATE_BIG \ - sph_u64 h[27]; \ - sph_u64 bcount; - -#define READ_STATE_BIG(sc) do { \ - h[0] = (sc)->h0; \ - h[1] = (sc)->h1; \ - h[2] = (sc)->h2; \ - h[3] = (sc)->h3; \ - h[4] = (sc)->h4; \ - h[5] = (sc)->h5; \ - h[6] = (sc)->h6; \ - h[7] = (sc)->h7; \ - bcount = sc->bcount; \ - } while (0) - -#define WRITE_STATE_BIG(sc) do { \ - (sc)->h0 = h[0]; \ - (sc)->h1 = h[1]; \ - (sc)->h2 = h[2]; \ - (sc)->h3 = h[3]; \ - (sc)->h4 = h[4]; \ - (sc)->h5 = h[5]; \ - (sc)->h6 = h[6]; \ - (sc)->h7 = h[7]; \ - sc->bcount = bcount; \ - } while (0) - -#else - -#define DECL_STATE_BIG \ - sph_u64 h0, h1, h2, h3, h4, h5, h6, h7; \ - sph_u64 bcount; - -#define READ_STATE_BIG(sc) do { \ - h0 = (sc)->h0; \ - h1 = (sc)->h1; \ - h2 = (sc)->h2; \ - h3 = (sc)->h3; \ - h4 = (sc)->h4; \ - h5 = (sc)->h5; \ - h6 = (sc)->h6; \ - h7 = (sc)->h7; \ - bcount = sc->bcount; \ - } while (0) - -#define WRITE_STATE_BIG(sc) do { \ - (sc)->h0 = h0; \ - (sc)->h1 = h1; \ - (sc)->h2 = h2; \ - (sc)->h3 = h3; \ - (sc)->h4 = h4; \ - (sc)->h5 = h5; \ - (sc)->h6 = h6; \ - (sc)->h7 = h7; \ - sc->bcount = bcount; \ - } while (0) - -#endif - -#if 0 -/* obsolete */ -static void -skein_small_init(sph_skein_small_context *sc, const sph_u64 *iv) -{ - sc->h0 = iv[0]; - sc->h1 = iv[1]; - sc->h2 = iv[2]; - sc->h3 = iv[3]; - sc->bcount = 0; - sc->ptr = 0; -} -#endif - -static void -skein_big_init(sph_skein_big_context *sc, const sph_u64 *iv) -{ - sc->h0 = iv[0]; - sc->h1 = iv[1]; - sc->h2 = iv[2]; - sc->h3 = iv[3]; - sc->h4 = iv[4]; - sc->h5 = iv[5]; - sc->h6 = iv[6]; - sc->h7 = iv[7]; - sc->bcount = 0; - sc->ptr = 0; -} - -#if 0 -/* obsolete */ -static void -skein_small_core(sph_skein_small_context *sc, const void *data, size_t len) -{ - unsigned char *buf; - size_t ptr, clen; - unsigned first; - DECL_STATE_SMALL - - buf = sc->buf; - ptr = sc->ptr; - clen = (sizeof sc->buf) - ptr; - if (len <= clen) { - memcpy(buf + ptr, data, len); - sc->ptr = ptr + len; - return; - } - if (clen != 0) { - memcpy(buf + ptr, data, clen); - data = (const unsigned char *)data + clen; - len -= clen; - } - -#if SPH_SMALL_FOOTPRINT_SKEIN - - READ_STATE_SMALL(sc); - first = (bcount == 0) << 7; - for (;;) { - bcount ++; - UBI_SMALL(96 + first, 0); - if (len <= sizeof sc->buf) - break; - first = 0; - memcpy(buf, data, sizeof sc->buf); - data = (const unsigned char *)data + sizeof sc->buf; - len -= sizeof sc->buf; - } - WRITE_STATE_SMALL(sc); - sc->ptr = len; - memcpy(buf, data, len); - -#else - - /* - * Unrolling the loop yields a slight performance boost, while - * keeping the code size aorund 24 kB on 32-bit x86. - */ - READ_STATE_SMALL(sc); - first = (bcount == 0) << 7; - for (;;) { - bcount ++; - UBI_SMALL(96 + first, 0); - if (len <= sizeof sc->buf) - break; - buf = (unsigned char *)data; - bcount ++; - UBI_SMALL(96, 0); - if (len <= 2 * sizeof sc->buf) { - data = buf + sizeof sc->buf; - len -= sizeof sc->buf; - break; - } - buf += sizeof sc->buf; - data = buf + sizeof sc->buf; - first = 0; - len -= 2 * sizeof sc->buf; - } - WRITE_STATE_SMALL(sc); - sc->ptr = len; - memcpy(sc->buf, data, len); - -#endif -} -#endif - -static void -skein_big_core(sph_skein_big_context *sc, const void *data, size_t len) -{ - /* - * The Skein "final bit" in the tweak is troublesome here, - * because if the input has a length which is a multiple of the - * block size (512 bits) then that bit must be set for the - * final block, which is full of message bits (padding in - * Skein can be reduced to no extra bit at all). However, this - * function cannot know whether it processes the last chunks of - * the message or not. Hence we may keep a full block of buffered - * data (64 bytes). - */ - unsigned char *buf; - size_t ptr; - unsigned first; - DECL_STATE_BIG - - buf = sc->buf; - ptr = sc->ptr; - if (len <= (sizeof sc->buf) - ptr) { - memcpy(buf + ptr, data, len); - ptr += len; - sc->ptr = ptr; - return; - } - - READ_STATE_BIG(sc); - first = (bcount == 0) << 7; - do { - size_t clen; - - if (ptr == sizeof sc->buf) { - bcount ++; - UBI_BIG(96 + first, 0); - first = 0; - ptr = 0; - } - clen = (sizeof sc->buf) - ptr; - if (clen > len) - clen = len; - memcpy(buf + ptr, data, clen); - ptr += clen; - data = (const unsigned char *)data + clen; - len -= clen; - } while (len > 0); - WRITE_STATE_BIG(sc); - sc->ptr = ptr; -} - -#if 0 -/* obsolete */ -static void -skein_small_close(sph_skein_small_context *sc, unsigned ub, unsigned n, - void *dst, size_t out_len) -{ - unsigned char *buf; - size_t ptr; - unsigned et; - int i; - DECL_STATE_SMALL - - if (n != 0) { - unsigned z; - unsigned char x; - - z = 0x80 >> n; - x = ((ub & -z) | z) & 0xFF; - skein_small_core(sc, &x, 1); - } - - buf = sc->buf; - ptr = sc->ptr; - READ_STATE_SMALL(sc); - memset(buf + ptr, 0, (sizeof sc->buf) - ptr); - et = 352 + ((bcount == 0) << 7) + (n != 0); - for (i = 0; i < 2; i ++) { - UBI_SMALL(et, ptr); - if (i == 0) { - memset(buf, 0, sizeof sc->buf); - bcount = 0; - et = 510; - ptr = 8; - } - } - - sph_enc64le_aligned(buf + 0, h0); - sph_enc64le_aligned(buf + 8, h1); - sph_enc64le_aligned(buf + 16, h2); - sph_enc64le_aligned(buf + 24, h3); - memcpy(dst, buf, out_len); -} -#endif - -static void -skein_big_close(sph_skein_big_context *sc, unsigned ub, unsigned n, - void *dst, size_t out_len) -{ - unsigned char *buf; - size_t ptr; - unsigned et; - int i; -#if SPH_SMALL_FOOTPRINT_SKEIN - size_t u; -#endif - DECL_STATE_BIG - - /* - * Add bit padding if necessary. - */ - if (n != 0) { - unsigned z; - unsigned char x; - - z = 0x80 >> n; - x = ((ub & -z) | z) & 0xFF; - skein_big_core(sc, &x, 1); - } - - buf = sc->buf; - ptr = sc->ptr; - - /* - * At that point, if ptr == 0, then the message was empty; - * otherwise, there is between 1 and 64 bytes (inclusive) which - * are yet to be processed. Either way, we complete the buffer - * to a full block with zeros (the Skein specification mandates - * that an empty message is padded so that there is at least - * one block to process). - * - * Once this block has been processed, we do it again, with - * a block full of zeros, for the output (that block contains - * the encoding of "0", over 8 bytes, then padded with zeros). - */ - READ_STATE_BIG(sc); - memset(buf + ptr, 0, (sizeof sc->buf) - ptr); - et = 352 + ((bcount == 0) << 7) + (n != 0); - for (i = 0; i < 2; i ++) { - UBI_BIG(et, ptr); - if (i == 0) { - memset(buf, 0, sizeof sc->buf); - bcount = 0; - et = 510; - ptr = 8; - } - } - -#if SPH_SMALL_FOOTPRINT_SKEIN - - /* - * We use a temporary buffer because we must support the case - * where output size is not a multiple of 64 (namely, a 224-bit - * output). - */ - for (u = 0; u < out_len; u += 8) - sph_enc64le_aligned(buf + u, h[u >> 3]); - memcpy(dst, buf, out_len); - -#else - - sph_enc64le_aligned(buf + 0, h0); - sph_enc64le_aligned(buf + 8, h1); - sph_enc64le_aligned(buf + 16, h2); - sph_enc64le_aligned(buf + 24, h3); - sph_enc64le_aligned(buf + 32, h4); - sph_enc64le_aligned(buf + 40, h5); - sph_enc64le_aligned(buf + 48, h6); - sph_enc64le_aligned(buf + 56, h7); - memcpy(dst, buf, out_len); - -#endif -} - -#if 0 -/* obsolete */ -static const sph_u64 IV224[] = { - SPH_C64(0xC6098A8C9AE5EA0B), SPH_C64(0x876D568608C5191C), - SPH_C64(0x99CB88D7D7F53884), SPH_C64(0x384BDDB1AEDDB5DE) -}; - -static const sph_u64 IV256[] = { - SPH_C64(0xFC9DA860D048B449), SPH_C64(0x2FCA66479FA7D833), - SPH_C64(0xB33BC3896656840F), SPH_C64(0x6A54E920FDE8DA69) -}; -#endif - -static const sph_u64 IV224[] = { - SPH_C64(0xCCD0616248677224), SPH_C64(0xCBA65CF3A92339EF), - SPH_C64(0x8CCD69D652FF4B64), SPH_C64(0x398AED7B3AB890B4), - SPH_C64(0x0F59D1B1457D2BD0), SPH_C64(0x6776FE6575D4EB3D), - SPH_C64(0x99FBC70E997413E9), SPH_C64(0x9E2CFCCFE1C41EF7) -}; - -static const sph_u64 IV256[] = { - SPH_C64(0xCCD044A12FDB3E13), SPH_C64(0xE83590301A79A9EB), - SPH_C64(0x55AEA0614F816E6F), SPH_C64(0x2A2767A4AE9B94DB), - SPH_C64(0xEC06025E74DD7683), SPH_C64(0xE7A436CDC4746251), - SPH_C64(0xC36FBAF9393AD185), SPH_C64(0x3EEDBA1833EDFC13) -}; - -static const sph_u64 IV384[] = { - SPH_C64(0xA3F6C6BF3A75EF5F), SPH_C64(0xB0FEF9CCFD84FAA4), - SPH_C64(0x9D77DD663D770CFE), SPH_C64(0xD798CBF3B468FDDA), - SPH_C64(0x1BC4A6668A0E4465), SPH_C64(0x7ED7D434E5807407), - SPH_C64(0x548FC1ACD4EC44D6), SPH_C64(0x266E17546AA18FF8) -}; - -static const sph_u64 IV512[] = { - SPH_C64(0x4903ADFF749C51CE), SPH_C64(0x0D95DE399746DF03), - SPH_C64(0x8FD1934127C79BCE), SPH_C64(0x9A255629FF352CB1), - SPH_C64(0x5DB62599DF6CA7B0), SPH_C64(0xEABE394CA9D5C3F4), - SPH_C64(0x991112C71A75B523), SPH_C64(0xAE18A40B660FCC33) -}; - -#if 0 -/* obsolete */ -/* see sph_skein.h */ -void -sph_skein224_init(void *cc) -{ - skein_small_init(cc, IV224); -} - -/* see sph_skein.h */ -void -sph_skein224(void *cc, const void *data, size_t len) -{ - skein_small_core(cc, data, len); -} - -/* see sph_skein.h */ -void -sph_skein224_close(void *cc, void *dst) -{ - sph_skein224_addbits_and_close(cc, 0, 0, dst); -} - -/* see sph_skein.h */ -void -sph_skein224_addbits_and_close(void *cc, unsigned ub, unsigned n, void *dst) -{ - skein_small_close(cc, ub, n, dst, 28); - sph_skein224_init(cc); -} - -/* see sph_skein.h */ -void -sph_skein256_init(void *cc) -{ - skein_small_init(cc, IV256); -} - -/* see sph_skein.h */ -void -sph_skein256(void *cc, const void *data, size_t len) -{ - skein_small_core(cc, data, len); -} - -/* see sph_skein.h */ -void -sph_skein256_close(void *cc, void *dst) -{ - sph_skein256_addbits_and_close(cc, 0, 0, dst); -} - -/* see sph_skein.h */ -void -sph_skein256_addbits_and_close(void *cc, unsigned ub, unsigned n, void *dst) -{ - skein_small_close(cc, ub, n, dst, 32); - sph_skein256_init(cc); -} -#endif - -/* see sph_skein.h */ -void -sph_skein224_init(void *cc) -{ - skein_big_init(cc, IV224); -} - -/* see sph_skein.h */ -void -sph_skein224(void *cc, const void *data, size_t len) -{ - skein_big_core(cc, data, len); -} - -/* see sph_skein.h */ -void -sph_skein224_close(void *cc, void *dst) -{ - sph_skein224_addbits_and_close(cc, 0, 0, dst); -} - -/* see sph_skein.h */ -void -sph_skein224_addbits_and_close(void *cc, unsigned ub, unsigned n, void *dst) -{ - skein_big_close(cc, ub, n, dst, 28); - sph_skein224_init(cc); -} - -/* see sph_skein.h */ -void -sph_skein256_init(void *cc) -{ - skein_big_init(cc, IV256); -} - -/* see sph_skein.h */ -void -sph_skein256(void *cc, const void *data, size_t len) -{ - skein_big_core(cc, data, len); -} - -/* see sph_skein.h */ -void -sph_skein256_close(void *cc, void *dst) -{ - sph_skein256_addbits_and_close(cc, 0, 0, dst); -} - -/* see sph_skein.h */ -void -sph_skein256_addbits_and_close(void *cc, unsigned ub, unsigned n, void *dst) -{ - skein_big_close(cc, ub, n, dst, 32); - sph_skein256_init(cc); -} - -/* see sph_skein.h */ -void -sph_skein384_init(void *cc) -{ - skein_big_init(cc, IV384); -} - -/* see sph_skein.h */ -void -sph_skein384(void *cc, const void *data, size_t len) -{ - skein_big_core(cc, data, len); -} - -/* see sph_skein.h */ -void -sph_skein384_close(void *cc, void *dst) -{ - sph_skein384_addbits_and_close(cc, 0, 0, dst); -} - -/* see sph_skein.h */ -void -sph_skein384_addbits_and_close(void *cc, unsigned ub, unsigned n, void *dst) -{ - skein_big_close(cc, ub, n, dst, 48); - sph_skein384_init(cc); -} - -/* see sph_skein.h */ -void -sph_skein512_init(void *cc) -{ - skein_big_init(cc, IV512); -} - -/* see sph_skein.h */ -void -sph_skein512(void *cc, const void *data, size_t len) -{ - skein_big_core(cc, data, len); -} - -/* see sph_skein.h */ -void -sph_skein512_close(void *cc, void *dst) -{ - sph_skein512_addbits_and_close(cc, 0, 0, dst); -} - -/* see sph_skein.h */ -void -sph_skein512_addbits_and_close(void *cc, unsigned ub, unsigned n, void *dst) -{ - skein_big_close(cc, ub, n, dst, 64); - sph_skein512_init(cc); -} - -#endif - - -#ifdef __cplusplus -} -#endif diff --git a/src/crypto/sph_blake.h b/src/crypto/sph_blake.h deleted file mode 100644 index d8d794399d00..000000000000 --- a/src/crypto/sph_blake.h +++ /dev/null @@ -1,327 +0,0 @@ -/* $Id: sph_blake.h 252 2011-06-07 17:55:14Z tp $ */ -/** - * BLAKE interface. BLAKE is a family of functions which differ by their - * output size; this implementation defines BLAKE for output sizes 224, - * 256, 384 and 512 bits. This implementation conforms to the "third - * round" specification. - * - * ==========================(LICENSE BEGIN)============================ - * - * Copyright (c) 2007-2010 Projet RNRT SAPHIR - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY - * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, - * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE - * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - * ===========================(LICENSE END)============================= - * - * @file sph_blake.h - * @author Thomas Pornin - */ - -#ifndef SPH_BLAKE_H__ -#define SPH_BLAKE_H__ - -#ifdef __cplusplus -extern "C"{ -#endif - -#include -#include "sph_types.h" - -/** - * Output size (in bits) for BLAKE-224. - */ -#define SPH_SIZE_blake224 224 - -/** - * Output size (in bits) for BLAKE-256. - */ -#define SPH_SIZE_blake256 256 - -#if SPH_64 - -/** - * Output size (in bits) for BLAKE-384. - */ -#define SPH_SIZE_blake384 384 - -/** - * Output size (in bits) for BLAKE-512. - */ -#define SPH_SIZE_blake512 512 - -#endif - -/** - * This structure is a context for BLAKE-224 and BLAKE-256 computations: - * it contains the intermediate values and some data from the last - * entered block. Once a BLAKE computation has been performed, the - * context can be reused for another computation. - * - * The contents of this structure are private. A running BLAKE - * computation can be cloned by copying the context (e.g. with a simple - * memcpy()). - */ -typedef struct { -#ifndef DOXYGEN_IGNORE - unsigned char buf[64]; /* first field, for alignment */ - size_t ptr; - sph_u32 H[8]; - sph_u32 S[4]; - sph_u32 T0, T1; -#endif -} sph_blake_small_context; - -/** - * This structure is a context for BLAKE-224 computations. It is - * identical to the common sph_blake_small_context. - */ -typedef sph_blake_small_context sph_blake224_context; - -/** - * This structure is a context for BLAKE-256 computations. It is - * identical to the common sph_blake_small_context. - */ -typedef sph_blake_small_context sph_blake256_context; - -#if SPH_64 - -/** - * This structure is a context for BLAKE-384 and BLAKE-512 computations: - * it contains the intermediate values and some data from the last - * entered block. Once a BLAKE computation has been performed, the - * context can be reused for another computation. - * - * The contents of this structure are private. A running BLAKE - * computation can be cloned by copying the context (e.g. with a simple - * memcpy()). - */ -typedef struct { -#ifndef DOXYGEN_IGNORE - unsigned char buf[128]; /* first field, for alignment */ - size_t ptr; - sph_u64 H[8]; - sph_u64 S[4]; - sph_u64 T0, T1; -#endif -} sph_blake_big_context; - -/** - * This structure is a context for BLAKE-384 computations. It is - * identical to the common sph_blake_small_context. - */ -typedef sph_blake_big_context sph_blake384_context; - -/** - * This structure is a context for BLAKE-512 computations. It is - * identical to the common sph_blake_small_context. - */ -typedef sph_blake_big_context sph_blake512_context; - -#endif - -/** - * Initialize a BLAKE-224 context. This process performs no memory allocation. - * - * @param cc the BLAKE-224 context (pointer to a - * sph_blake224_context) - */ -void sph_blake224_init(void *cc); - -/** - * Process some data bytes. It is acceptable that len is zero - * (in which case this function does nothing). - * - * @param cc the BLAKE-224 context - * @param data the input data - * @param len the input data length (in bytes) - */ -void sph_blake224(void *cc, const void *data, size_t len); - -/** - * Terminate the current BLAKE-224 computation and output the result into - * the provided buffer. The destination buffer must be wide enough to - * accomodate the result (28 bytes). The context is automatically - * reinitialized. - * - * @param cc the BLAKE-224 context - * @param dst the destination buffer - */ -void sph_blake224_close(void *cc, void *dst); - -/** - * Add a few additional bits (0 to 7) to the current computation, then - * terminate it and output the result in the provided buffer, which must - * be wide enough to accomodate the result (28 bytes). If bit number i - * in ub has value 2^i, then the extra bits are those - * numbered 7 downto 8-n (this is the big-endian convention at the byte - * level). The context is automatically reinitialized. - * - * @param cc the BLAKE-224 context - * @param ub the extra bits - * @param n the number of extra bits (0 to 7) - * @param dst the destination buffer - */ -void sph_blake224_addbits_and_close( - void *cc, unsigned ub, unsigned n, void *dst); - -/** - * Initialize a BLAKE-256 context. This process performs no memory allocation. - * - * @param cc the BLAKE-256 context (pointer to a - * sph_blake256_context) - */ -void sph_blake256_init(void *cc); - -/** - * Process some data bytes. It is acceptable that len is zero - * (in which case this function does nothing). - * - * @param cc the BLAKE-256 context - * @param data the input data - * @param len the input data length (in bytes) - */ -void sph_blake256(void *cc, const void *data, size_t len); - -/** - * Terminate the current BLAKE-256 computation and output the result into - * the provided buffer. The destination buffer must be wide enough to - * accomodate the result (32 bytes). The context is automatically - * reinitialized. - * - * @param cc the BLAKE-256 context - * @param dst the destination buffer - */ -void sph_blake256_close(void *cc, void *dst); - -/** - * Add a few additional bits (0 to 7) to the current computation, then - * terminate it and output the result in the provided buffer, which must - * be wide enough to accomodate the result (32 bytes). If bit number i - * in ub has value 2^i, then the extra bits are those - * numbered 7 downto 8-n (this is the big-endian convention at the byte - * level). The context is automatically reinitialized. - * - * @param cc the BLAKE-256 context - * @param ub the extra bits - * @param n the number of extra bits (0 to 7) - * @param dst the destination buffer - */ -void sph_blake256_addbits_and_close( - void *cc, unsigned ub, unsigned n, void *dst); - -#if SPH_64 - -/** - * Initialize a BLAKE-384 context. This process performs no memory allocation. - * - * @param cc the BLAKE-384 context (pointer to a - * sph_blake384_context) - */ -void sph_blake384_init(void *cc); - -/** - * Process some data bytes. It is acceptable that len is zero - * (in which case this function does nothing). - * - * @param cc the BLAKE-384 context - * @param data the input data - * @param len the input data length (in bytes) - */ -void sph_blake384(void *cc, const void *data, size_t len); - -/** - * Terminate the current BLAKE-384 computation and output the result into - * the provided buffer. The destination buffer must be wide enough to - * accomodate the result (48 bytes). The context is automatically - * reinitialized. - * - * @param cc the BLAKE-384 context - * @param dst the destination buffer - */ -void sph_blake384_close(void *cc, void *dst); - -/** - * Add a few additional bits (0 to 7) to the current computation, then - * terminate it and output the result in the provided buffer, which must - * be wide enough to accomodate the result (48 bytes). If bit number i - * in ub has value 2^i, then the extra bits are those - * numbered 7 downto 8-n (this is the big-endian convention at the byte - * level). The context is automatically reinitialized. - * - * @param cc the BLAKE-384 context - * @param ub the extra bits - * @param n the number of extra bits (0 to 7) - * @param dst the destination buffer - */ -void sph_blake384_addbits_and_close( - void *cc, unsigned ub, unsigned n, void *dst); - -/** - * Initialize a BLAKE-512 context. This process performs no memory allocation. - * - * @param cc the BLAKE-512 context (pointer to a - * sph_blake512_context) - */ -void sph_blake512_init(void *cc); - -/** - * Process some data bytes. It is acceptable that len is zero - * (in which case this function does nothing). - * - * @param cc the BLAKE-512 context - * @param data the input data - * @param len the input data length (in bytes) - */ -void sph_blake512(void *cc, const void *data, size_t len); - -/** - * Terminate the current BLAKE-512 computation and output the result into - * the provided buffer. The destination buffer must be wide enough to - * accomodate the result (64 bytes). The context is automatically - * reinitialized. - * - * @param cc the BLAKE-512 context - * @param dst the destination buffer - */ -void sph_blake512_close(void *cc, void *dst); - -/** - * Add a few additional bits (0 to 7) to the current computation, then - * terminate it and output the result in the provided buffer, which must - * be wide enough to accomodate the result (64 bytes). If bit number i - * in ub has value 2^i, then the extra bits are those - * numbered 7 downto 8-n (this is the big-endian convention at the byte - * level). The context is automatically reinitialized. - * - * @param cc the BLAKE-512 context - * @param ub the extra bits - * @param n the number of extra bits (0 to 7) - * @param dst the destination buffer - */ -void sph_blake512_addbits_and_close( - void *cc, unsigned ub, unsigned n, void *dst); - -#endif - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/src/crypto/sph_bmw.h b/src/crypto/sph_bmw.h deleted file mode 100644 index d386b0c14053..000000000000 --- a/src/crypto/sph_bmw.h +++ /dev/null @@ -1,328 +0,0 @@ -/* $Id: sph_bmw.h 216 2010-06-08 09:46:57Z tp $ */ -/** - * BMW interface. BMW (aka "Blue Midnight Wish") is a family of - * functions which differ by their output size; this implementation - * defines BMW for output sizes 224, 256, 384 and 512 bits. - * - * ==========================(LICENSE BEGIN)============================ - * - * Copyright (c) 2007-2010 Projet RNRT SAPHIR - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY - * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, - * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE - * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - * ===========================(LICENSE END)============================= - * - * @file sph_bmw.h - * @author Thomas Pornin - */ - -#ifndef SPH_BMW_H__ -#define SPH_BMW_H__ - -#ifdef __cplusplus -extern "C"{ -#endif - -#include -#include "sph_types.h" - -/** - * Output size (in bits) for BMW-224. - */ -#define SPH_SIZE_bmw224 224 - -/** - * Output size (in bits) for BMW-256. - */ -#define SPH_SIZE_bmw256 256 - -#if SPH_64 - -/** - * Output size (in bits) for BMW-384. - */ -#define SPH_SIZE_bmw384 384 - -/** - * Output size (in bits) for BMW-512. - */ -#define SPH_SIZE_bmw512 512 - -#endif - -/** - * This structure is a context for BMW-224 and BMW-256 computations: - * it contains the intermediate values and some data from the last - * entered block. Once a BMW computation has been performed, the - * context can be reused for another computation. - * - * The contents of this structure are private. A running BMW - * computation can be cloned by copying the context (e.g. with a simple - * memcpy()). - */ -typedef struct { -#ifndef DOXYGEN_IGNORE - unsigned char buf[64]; /* first field, for alignment */ - size_t ptr; - sph_u32 H[16]; -#if SPH_64 - sph_u64 bit_count; -#else - sph_u32 bit_count_high, bit_count_low; -#endif -#endif -} sph_bmw_small_context; - -/** - * This structure is a context for BMW-224 computations. It is - * identical to the common sph_bmw_small_context. - */ -typedef sph_bmw_small_context sph_bmw224_context; - -/** - * This structure is a context for BMW-256 computations. It is - * identical to the common sph_bmw_small_context. - */ -typedef sph_bmw_small_context sph_bmw256_context; - -#if SPH_64 - -/** - * This structure is a context for BMW-384 and BMW-512 computations: - * it contains the intermediate values and some data from the last - * entered block. Once a BMW computation has been performed, the - * context can be reused for another computation. - * - * The contents of this structure are private. A running BMW - * computation can be cloned by copying the context (e.g. with a simple - * memcpy()). - */ -typedef struct { -#ifndef DOXYGEN_IGNORE - unsigned char buf[128]; /* first field, for alignment */ - size_t ptr; - sph_u64 H[16]; - sph_u64 bit_count; -#endif -} sph_bmw_big_context; - -/** - * This structure is a context for BMW-384 computations. It is - * identical to the common sph_bmw_small_context. - */ -typedef sph_bmw_big_context sph_bmw384_context; - -/** - * This structure is a context for BMW-512 computations. It is - * identical to the common sph_bmw_small_context. - */ -typedef sph_bmw_big_context sph_bmw512_context; - -#endif - -/** - * Initialize a BMW-224 context. This process performs no memory allocation. - * - * @param cc the BMW-224 context (pointer to a - * sph_bmw224_context) - */ -void sph_bmw224_init(void *cc); - -/** - * Process some data bytes. It is acceptable that len is zero - * (in which case this function does nothing). - * - * @param cc the BMW-224 context - * @param data the input data - * @param len the input data length (in bytes) - */ -void sph_bmw224(void *cc, const void *data, size_t len); - -/** - * Terminate the current BMW-224 computation and output the result into - * the provided buffer. The destination buffer must be wide enough to - * accomodate the result (28 bytes). The context is automatically - * reinitialized. - * - * @param cc the BMW-224 context - * @param dst the destination buffer - */ -void sph_bmw224_close(void *cc, void *dst); - -/** - * Add a few additional bits (0 to 7) to the current computation, then - * terminate it and output the result in the provided buffer, which must - * be wide enough to accomodate the result (28 bytes). If bit number i - * in ub has value 2^i, then the extra bits are those - * numbered 7 downto 8-n (this is the big-endian convention at the byte - * level). The context is automatically reinitialized. - * - * @param cc the BMW-224 context - * @param ub the extra bits - * @param n the number of extra bits (0 to 7) - * @param dst the destination buffer - */ -void sph_bmw224_addbits_and_close( - void *cc, unsigned ub, unsigned n, void *dst); - -/** - * Initialize a BMW-256 context. This process performs no memory allocation. - * - * @param cc the BMW-256 context (pointer to a - * sph_bmw256_context) - */ -void sph_bmw256_init(void *cc); - -/** - * Process some data bytes. It is acceptable that len is zero - * (in which case this function does nothing). - * - * @param cc the BMW-256 context - * @param data the input data - * @param len the input data length (in bytes) - */ -void sph_bmw256(void *cc, const void *data, size_t len); - -/** - * Terminate the current BMW-256 computation and output the result into - * the provided buffer. The destination buffer must be wide enough to - * accomodate the result (32 bytes). The context is automatically - * reinitialized. - * - * @param cc the BMW-256 context - * @param dst the destination buffer - */ -void sph_bmw256_close(void *cc, void *dst); - -/** - * Add a few additional bits (0 to 7) to the current computation, then - * terminate it and output the result in the provided buffer, which must - * be wide enough to accomodate the result (32 bytes). If bit number i - * in ub has value 2^i, then the extra bits are those - * numbered 7 downto 8-n (this is the big-endian convention at the byte - * level). The context is automatically reinitialized. - * - * @param cc the BMW-256 context - * @param ub the extra bits - * @param n the number of extra bits (0 to 7) - * @param dst the destination buffer - */ -void sph_bmw256_addbits_and_close( - void *cc, unsigned ub, unsigned n, void *dst); - -#if SPH_64 - -/** - * Initialize a BMW-384 context. This process performs no memory allocation. - * - * @param cc the BMW-384 context (pointer to a - * sph_bmw384_context) - */ -void sph_bmw384_init(void *cc); - -/** - * Process some data bytes. It is acceptable that len is zero - * (in which case this function does nothing). - * - * @param cc the BMW-384 context - * @param data the input data - * @param len the input data length (in bytes) - */ -void sph_bmw384(void *cc, const void *data, size_t len); - -/** - * Terminate the current BMW-384 computation and output the result into - * the provided buffer. The destination buffer must be wide enough to - * accomodate the result (48 bytes). The context is automatically - * reinitialized. - * - * @param cc the BMW-384 context - * @param dst the destination buffer - */ -void sph_bmw384_close(void *cc, void *dst); - -/** - * Add a few additional bits (0 to 7) to the current computation, then - * terminate it and output the result in the provided buffer, which must - * be wide enough to accomodate the result (48 bytes). If bit number i - * in ub has value 2^i, then the extra bits are those - * numbered 7 downto 8-n (this is the big-endian convention at the byte - * level). The context is automatically reinitialized. - * - * @param cc the BMW-384 context - * @param ub the extra bits - * @param n the number of extra bits (0 to 7) - * @param dst the destination buffer - */ -void sph_bmw384_addbits_and_close( - void *cc, unsigned ub, unsigned n, void *dst); - -/** - * Initialize a BMW-512 context. This process performs no memory allocation. - * - * @param cc the BMW-512 context (pointer to a - * sph_bmw512_context) - */ -void sph_bmw512_init(void *cc); - -/** - * Process some data bytes. It is acceptable that len is zero - * (in which case this function does nothing). - * - * @param cc the BMW-512 context - * @param data the input data - * @param len the input data length (in bytes) - */ -void sph_bmw512(void *cc, const void *data, size_t len); - -/** - * Terminate the current BMW-512 computation and output the result into - * the provided buffer. The destination buffer must be wide enough to - * accomodate the result (64 bytes). The context is automatically - * reinitialized. - * - * @param cc the BMW-512 context - * @param dst the destination buffer - */ -void sph_bmw512_close(void *cc, void *dst); - -/** - * Add a few additional bits (0 to 7) to the current computation, then - * terminate it and output the result in the provided buffer, which must - * be wide enough to accomodate the result (64 bytes). If bit number i - * in ub has value 2^i, then the extra bits are those - * numbered 7 downto 8-n (this is the big-endian convention at the byte - * level). The context is automatically reinitialized. - * - * @param cc the BMW-512 context - * @param ub the extra bits - * @param n the number of extra bits (0 to 7) - * @param dst the destination buffer - */ -void sph_bmw512_addbits_and_close( - void *cc, unsigned ub, unsigned n, void *dst); - -#endif - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/src/crypto/sph_cubehash.h b/src/crypto/sph_cubehash.h deleted file mode 100644 index 487a1946ad40..000000000000 --- a/src/crypto/sph_cubehash.h +++ /dev/null @@ -1,292 +0,0 @@ -/* $Id: sph_cubehash.h 180 2010-05-08 02:29:25Z tp $ */ -/** - * CubeHash interface. CubeHash is a family of functions which differ by - * their output size; this implementation defines CubeHash for output - * sizes 224, 256, 384 and 512 bits, with the "standard parameters" - * (CubeHash16/32 with the CubeHash specification notations). - * - * ==========================(LICENSE BEGIN)============================ - * - * Copyright (c) 2007-2010 Projet RNRT SAPHIR - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY - * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, - * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE - * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - * ===========================(LICENSE END)============================= - * - * @file sph_cubehash.h - * @author Thomas Pornin - */ - -#ifndef SPH_CUBEHASH_H__ -#define SPH_CUBEHASH_H__ - -#ifdef __cplusplus -extern "C"{ -#endif - -#include -#include "sph_types.h" - -/** - * Output size (in bits) for CubeHash-224. - */ -#define SPH_SIZE_cubehash224 224 - -/** - * Output size (in bits) for CubeHash-256. - */ -#define SPH_SIZE_cubehash256 256 - -/** - * Output size (in bits) for CubeHash-384. - */ -#define SPH_SIZE_cubehash384 384 - -/** - * Output size (in bits) for CubeHash-512. - */ -#define SPH_SIZE_cubehash512 512 - -/** - * This structure is a context for CubeHash computations: it contains the - * intermediate values and some data from the last entered block. Once - * a CubeHash computation has been performed, the context can be reused for - * another computation. - * - * The contents of this structure are private. A running CubeHash computation - * can be cloned by copying the context (e.g. with a simple - * memcpy()). - */ -typedef struct { -#ifndef DOXYGEN_IGNORE - unsigned char buf[32]; /* first field, for alignment */ - size_t ptr; - sph_u32 state[32]; -#endif -} sph_cubehash_context; - -/** - * Type for a CubeHash-224 context (identical to the common context). - */ -typedef sph_cubehash_context sph_cubehash224_context; - -/** - * Type for a CubeHash-256 context (identical to the common context). - */ -typedef sph_cubehash_context sph_cubehash256_context; - -/** - * Type for a CubeHash-384 context (identical to the common context). - */ -typedef sph_cubehash_context sph_cubehash384_context; - -/** - * Type for a CubeHash-512 context (identical to the common context). - */ -typedef sph_cubehash_context sph_cubehash512_context; - -/** - * Initialize a CubeHash-224 context. This process performs no memory - * allocation. - * - * @param cc the CubeHash-224 context (pointer to a - * sph_cubehash224_context) - */ -void sph_cubehash224_init(void *cc); - -/** - * Process some data bytes. It is acceptable that len is zero - * (in which case this function does nothing). - * - * @param cc the CubeHash-224 context - * @param data the input data - * @param len the input data length (in bytes) - */ -void sph_cubehash224(void *cc, const void *data, size_t len); - -/** - * Terminate the current CubeHash-224 computation and output the result into - * the provided buffer. The destination buffer must be wide enough to - * accomodate the result (28 bytes). The context is automatically - * reinitialized. - * - * @param cc the CubeHash-224 context - * @param dst the destination buffer - */ -void sph_cubehash224_close(void *cc, void *dst); - -/** - * Add a few additional bits (0 to 7) to the current computation, then - * terminate it and output the result in the provided buffer, which must - * be wide enough to accomodate the result (28 bytes). If bit number i - * in ub has value 2^i, then the extra bits are those - * numbered 7 downto 8-n (this is the big-endian convention at the byte - * level). The context is automatically reinitialized. - * - * @param cc the CubeHash-224 context - * @param ub the extra bits - * @param n the number of extra bits (0 to 7) - * @param dst the destination buffer - */ -void sph_cubehash224_addbits_and_close( - void *cc, unsigned ub, unsigned n, void *dst); - -/** - * Initialize a CubeHash-256 context. This process performs no memory - * allocation. - * - * @param cc the CubeHash-256 context (pointer to a - * sph_cubehash256_context) - */ -void sph_cubehash256_init(void *cc); - -/** - * Process some data bytes. It is acceptable that len is zero - * (in which case this function does nothing). - * - * @param cc the CubeHash-256 context - * @param data the input data - * @param len the input data length (in bytes) - */ -void sph_cubehash256(void *cc, const void *data, size_t len); - -/** - * Terminate the current CubeHash-256 computation and output the result into - * the provided buffer. The destination buffer must be wide enough to - * accomodate the result (32 bytes). The context is automatically - * reinitialized. - * - * @param cc the CubeHash-256 context - * @param dst the destination buffer - */ -void sph_cubehash256_close(void *cc, void *dst); - -/** - * Add a few additional bits (0 to 7) to the current computation, then - * terminate it and output the result in the provided buffer, which must - * be wide enough to accomodate the result (32 bytes). If bit number i - * in ub has value 2^i, then the extra bits are those - * numbered 7 downto 8-n (this is the big-endian convention at the byte - * level). The context is automatically reinitialized. - * - * @param cc the CubeHash-256 context - * @param ub the extra bits - * @param n the number of extra bits (0 to 7) - * @param dst the destination buffer - */ -void sph_cubehash256_addbits_and_close( - void *cc, unsigned ub, unsigned n, void *dst); - -/** - * Initialize a CubeHash-384 context. This process performs no memory - * allocation. - * - * @param cc the CubeHash-384 context (pointer to a - * sph_cubehash384_context) - */ -void sph_cubehash384_init(void *cc); - -/** - * Process some data bytes. It is acceptable that len is zero - * (in which case this function does nothing). - * - * @param cc the CubeHash-384 context - * @param data the input data - * @param len the input data length (in bytes) - */ -void sph_cubehash384(void *cc, const void *data, size_t len); - -/** - * Terminate the current CubeHash-384 computation and output the result into - * the provided buffer. The destination buffer must be wide enough to - * accomodate the result (48 bytes). The context is automatically - * reinitialized. - * - * @param cc the CubeHash-384 context - * @param dst the destination buffer - */ -void sph_cubehash384_close(void *cc, void *dst); - -/** - * Add a few additional bits (0 to 7) to the current computation, then - * terminate it and output the result in the provided buffer, which must - * be wide enough to accomodate the result (48 bytes). If bit number i - * in ub has value 2^i, then the extra bits are those - * numbered 7 downto 8-n (this is the big-endian convention at the byte - * level). The context is automatically reinitialized. - * - * @param cc the CubeHash-384 context - * @param ub the extra bits - * @param n the number of extra bits (0 to 7) - * @param dst the destination buffer - */ -void sph_cubehash384_addbits_and_close( - void *cc, unsigned ub, unsigned n, void *dst); - -/** - * Initialize a CubeHash-512 context. This process performs no memory - * allocation. - * - * @param cc the CubeHash-512 context (pointer to a - * sph_cubehash512_context) - */ -void sph_cubehash512_init(void *cc); - -/** - * Process some data bytes. It is acceptable that len is zero - * (in which case this function does nothing). - * - * @param cc the CubeHash-512 context - * @param data the input data - * @param len the input data length (in bytes) - */ -void sph_cubehash512(void *cc, const void *data, size_t len); - -/** - * Terminate the current CubeHash-512 computation and output the result into - * the provided buffer. The destination buffer must be wide enough to - * accomodate the result (64 bytes). The context is automatically - * reinitialized. - * - * @param cc the CubeHash-512 context - * @param dst the destination buffer - */ -void sph_cubehash512_close(void *cc, void *dst); - -/** - * Add a few additional bits (0 to 7) to the current computation, then - * terminate it and output the result in the provided buffer, which must - * be wide enough to accomodate the result (64 bytes). If bit number i - * in ub has value 2^i, then the extra bits are those - * numbered 7 downto 8-n (this is the big-endian convention at the byte - * level). The context is automatically reinitialized. - * - * @param cc the CubeHash-512 context - * @param ub the extra bits - * @param n the number of extra bits (0 to 7) - * @param dst the destination buffer - */ -void sph_cubehash512_addbits_and_close( - void *cc, unsigned ub, unsigned n, void *dst); -#ifdef __cplusplus -} -#endif - -#endif diff --git a/src/crypto/sph_groestl.h b/src/crypto/sph_groestl.h deleted file mode 100644 index 495f05e21174..000000000000 --- a/src/crypto/sph_groestl.h +++ /dev/null @@ -1,329 +0,0 @@ -/* $Id: sph_groestl.h 216 2010-06-08 09:46:57Z tp $ */ -/** - * Groestl interface. This code implements Groestl with the recommended - * parameters for SHA-3, with outputs of 224, 256, 384 and 512 bits. - * - * ==========================(LICENSE BEGIN)============================ - * - * Copyright (c) 2007-2010 Projet RNRT SAPHIR - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY - * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, - * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE - * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - * ===========================(LICENSE END)============================= - * - * @file sph_groestl.h - * @author Thomas Pornin - */ - -#ifndef SPH_GROESTL_H__ -#define SPH_GROESTL_H__ - -#ifdef __cplusplus -extern "C"{ -#endif - -#include -#include "sph_types.h" - -/** - * Output size (in bits) for Groestl-224. - */ -#define SPH_SIZE_groestl224 224 - -/** - * Output size (in bits) for Groestl-256. - */ -#define SPH_SIZE_groestl256 256 - -/** - * Output size (in bits) for Groestl-384. - */ -#define SPH_SIZE_groestl384 384 - -/** - * Output size (in bits) for Groestl-512. - */ -#define SPH_SIZE_groestl512 512 - -/** - * This structure is a context for Groestl-224 and Groestl-256 computations: - * it contains the intermediate values and some data from the last - * entered block. Once a Groestl computation has been performed, the - * context can be reused for another computation. - * - * The contents of this structure are private. A running Groestl - * computation can be cloned by copying the context (e.g. with a simple - * memcpy()). - */ -typedef struct { -#ifndef DOXYGEN_IGNORE - unsigned char buf[64]; /* first field, for alignment */ - size_t ptr; - union { -#if SPH_64 - sph_u64 wide[8]; -#endif - sph_u32 narrow[16]; - } state; -#if SPH_64 - sph_u64 count; -#else - sph_u32 count_high, count_low; -#endif -#endif -} sph_groestl_small_context; - -/** - * This structure is a context for Groestl-224 computations. It is - * identical to the common sph_groestl_small_context. - */ -typedef sph_groestl_small_context sph_groestl224_context; - -/** - * This structure is a context for Groestl-256 computations. It is - * identical to the common sph_groestl_small_context. - */ -typedef sph_groestl_small_context sph_groestl256_context; - -/** - * This structure is a context for Groestl-384 and Groestl-512 computations: - * it contains the intermediate values and some data from the last - * entered block. Once a Groestl computation has been performed, the - * context can be reused for another computation. - * - * The contents of this structure are private. A running Groestl - * computation can be cloned by copying the context (e.g. with a simple - * memcpy()). - */ -typedef struct { -#ifndef DOXYGEN_IGNORE - unsigned char buf[128]; /* first field, for alignment */ - size_t ptr; - union { -#if SPH_64 - sph_u64 wide[16]; -#endif - sph_u32 narrow[32]; - } state; -#if SPH_64 - sph_u64 count; -#else - sph_u32 count_high, count_low; -#endif -#endif -} sph_groestl_big_context; - -/** - * This structure is a context for Groestl-384 computations. It is - * identical to the common sph_groestl_small_context. - */ -typedef sph_groestl_big_context sph_groestl384_context; - -/** - * This structure is a context for Groestl-512 computations. It is - * identical to the common sph_groestl_small_context. - */ -typedef sph_groestl_big_context sph_groestl512_context; - -/** - * Initialize a Groestl-224 context. This process performs no memory allocation. - * - * @param cc the Groestl-224 context (pointer to a - * sph_groestl224_context) - */ -void sph_groestl224_init(void *cc); - -/** - * Process some data bytes. It is acceptable that len is zero - * (in which case this function does nothing). - * - * @param cc the Groestl-224 context - * @param data the input data - * @param len the input data length (in bytes) - */ -void sph_groestl224(void *cc, const void *data, size_t len); - -/** - * Terminate the current Groestl-224 computation and output the result into - * the provided buffer. The destination buffer must be wide enough to - * accomodate the result (28 bytes). The context is automatically - * reinitialized. - * - * @param cc the Groestl-224 context - * @param dst the destination buffer - */ -void sph_groestl224_close(void *cc, void *dst); - -/** - * Add a few additional bits (0 to 7) to the current computation, then - * terminate it and output the result in the provided buffer, which must - * be wide enough to accomodate the result (28 bytes). If bit number i - * in ub has value 2^i, then the extra bits are those - * numbered 7 downto 8-n (this is the big-endian convention at the byte - * level). The context is automatically reinitialized. - * - * @param cc the Groestl-224 context - * @param ub the extra bits - * @param n the number of extra bits (0 to 7) - * @param dst the destination buffer - */ -void sph_groestl224_addbits_and_close( - void *cc, unsigned ub, unsigned n, void *dst); - -/** - * Initialize a Groestl-256 context. This process performs no memory allocation. - * - * @param cc the Groestl-256 context (pointer to a - * sph_groestl256_context) - */ -void sph_groestl256_init(void *cc); - -/** - * Process some data bytes. It is acceptable that len is zero - * (in which case this function does nothing). - * - * @param cc the Groestl-256 context - * @param data the input data - * @param len the input data length (in bytes) - */ -void sph_groestl256(void *cc, const void *data, size_t len); - -/** - * Terminate the current Groestl-256 computation and output the result into - * the provided buffer. The destination buffer must be wide enough to - * accomodate the result (32 bytes). The context is automatically - * reinitialized. - * - * @param cc the Groestl-256 context - * @param dst the destination buffer - */ -void sph_groestl256_close(void *cc, void *dst); - -/** - * Add a few additional bits (0 to 7) to the current computation, then - * terminate it and output the result in the provided buffer, which must - * be wide enough to accomodate the result (32 bytes). If bit number i - * in ub has value 2^i, then the extra bits are those - * numbered 7 downto 8-n (this is the big-endian convention at the byte - * level). The context is automatically reinitialized. - * - * @param cc the Groestl-256 context - * @param ub the extra bits - * @param n the number of extra bits (0 to 7) - * @param dst the destination buffer - */ -void sph_groestl256_addbits_and_close( - void *cc, unsigned ub, unsigned n, void *dst); - -/** - * Initialize a Groestl-384 context. This process performs no memory allocation. - * - * @param cc the Groestl-384 context (pointer to a - * sph_groestl384_context) - */ -void sph_groestl384_init(void *cc); - -/** - * Process some data bytes. It is acceptable that len is zero - * (in which case this function does nothing). - * - * @param cc the Groestl-384 context - * @param data the input data - * @param len the input data length (in bytes) - */ -void sph_groestl384(void *cc, const void *data, size_t len); - -/** - * Terminate the current Groestl-384 computation and output the result into - * the provided buffer. The destination buffer must be wide enough to - * accomodate the result (48 bytes). The context is automatically - * reinitialized. - * - * @param cc the Groestl-384 context - * @param dst the destination buffer - */ -void sph_groestl384_close(void *cc, void *dst); - -/** - * Add a few additional bits (0 to 7) to the current computation, then - * terminate it and output the result in the provided buffer, which must - * be wide enough to accomodate the result (48 bytes). If bit number i - * in ub has value 2^i, then the extra bits are those - * numbered 7 downto 8-n (this is the big-endian convention at the byte - * level). The context is automatically reinitialized. - * - * @param cc the Groestl-384 context - * @param ub the extra bits - * @param n the number of extra bits (0 to 7) - * @param dst the destination buffer - */ -void sph_groestl384_addbits_and_close( - void *cc, unsigned ub, unsigned n, void *dst); - -/** - * Initialize a Groestl-512 context. This process performs no memory allocation. - * - * @param cc the Groestl-512 context (pointer to a - * sph_groestl512_context) - */ -void sph_groestl512_init(void *cc); - -/** - * Process some data bytes. It is acceptable that len is zero - * (in which case this function does nothing). - * - * @param cc the Groestl-512 context - * @param data the input data - * @param len the input data length (in bytes) - */ -void sph_groestl512(void *cc, const void *data, size_t len); - -/** - * Terminate the current Groestl-512 computation and output the result into - * the provided buffer. The destination buffer must be wide enough to - * accomodate the result (64 bytes). The context is automatically - * reinitialized. - * - * @param cc the Groestl-512 context - * @param dst the destination buffer - */ -void sph_groestl512_close(void *cc, void *dst); - -/** - * Add a few additional bits (0 to 7) to the current computation, then - * terminate it and output the result in the provided buffer, which must - * be wide enough to accomodate the result (64 bytes). If bit number i - * in ub has value 2^i, then the extra bits are those - * numbered 7 downto 8-n (this is the big-endian convention at the byte - * level). The context is automatically reinitialized. - * - * @param cc the Groestl-512 context - * @param ub the extra bits - * @param n the number of extra bits (0 to 7) - * @param dst the destination buffer - */ -void sph_groestl512_addbits_and_close( - void *cc, unsigned ub, unsigned n, void *dst); - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/src/crypto/sph_keccak.h b/src/crypto/sph_keccak.h deleted file mode 100644 index bdafdb88db02..000000000000 --- a/src/crypto/sph_keccak.h +++ /dev/null @@ -1,293 +0,0 @@ -/* $Id: sph_keccak.h 216 2010-06-08 09:46:57Z tp $ */ -/** - * Keccak interface. This is the interface for Keccak with the - * recommended parameters for SHA-3, with output lengths 224, 256, - * 384 and 512 bits. - * - * ==========================(LICENSE BEGIN)============================ - * - * Copyright (c) 2007-2010 Projet RNRT SAPHIR - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY - * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, - * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE - * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - * ===========================(LICENSE END)============================= - * - * @file sph_keccak.h - * @author Thomas Pornin - */ - -#ifndef SPH_KECCAK_H__ -#define SPH_KECCAK_H__ - -#ifdef __cplusplus -extern "C"{ -#endif - -#include -#include "sph_types.h" - -/** - * Output size (in bits) for Keccak-224. - */ -#define SPH_SIZE_keccak224 224 - -/** - * Output size (in bits) for Keccak-256. - */ -#define SPH_SIZE_keccak256 256 - -/** - * Output size (in bits) for Keccak-384. - */ -#define SPH_SIZE_keccak384 384 - -/** - * Output size (in bits) for Keccak-512. - */ -#define SPH_SIZE_keccak512 512 - -/** - * This structure is a context for Keccak computations: it contains the - * intermediate values and some data from the last entered block. Once a - * Keccak computation has been performed, the context can be reused for - * another computation. - * - * The contents of this structure are private. A running Keccak computation - * can be cloned by copying the context (e.g. with a simple - * memcpy()). - */ -typedef struct { -#ifndef DOXYGEN_IGNORE - unsigned char buf[144]; /* first field, for alignment */ - size_t ptr, lim; - union { -#if SPH_64 - sph_u64 wide[25]; -#endif - sph_u32 narrow[50]; - } u; -#endif -} sph_keccak_context; - -/** - * Type for a Keccak-224 context (identical to the common context). - */ -typedef sph_keccak_context sph_keccak224_context; - -/** - * Type for a Keccak-256 context (identical to the common context). - */ -typedef sph_keccak_context sph_keccak256_context; - -/** - * Type for a Keccak-384 context (identical to the common context). - */ -typedef sph_keccak_context sph_keccak384_context; - -/** - * Type for a Keccak-512 context (identical to the common context). - */ -typedef sph_keccak_context sph_keccak512_context; - -/** - * Initialize a Keccak-224 context. This process performs no memory allocation. - * - * @param cc the Keccak-224 context (pointer to a - * sph_keccak224_context) - */ -void sph_keccak224_init(void *cc); - -/** - * Process some data bytes. It is acceptable that len is zero - * (in which case this function does nothing). - * - * @param cc the Keccak-224 context - * @param data the input data - * @param len the input data length (in bytes) - */ -void sph_keccak224(void *cc, const void *data, size_t len); - -/** - * Terminate the current Keccak-224 computation and output the result into - * the provided buffer. The destination buffer must be wide enough to - * accomodate the result (28 bytes). The context is automatically - * reinitialized. - * - * @param cc the Keccak-224 context - * @param dst the destination buffer - */ -void sph_keccak224_close(void *cc, void *dst); - -/** - * Add a few additional bits (0 to 7) to the current computation, then - * terminate it and output the result in the provided buffer, which must - * be wide enough to accomodate the result (28 bytes). If bit number i - * in ub has value 2^i, then the extra bits are those - * numbered 7 downto 8-n (this is the big-endian convention at the byte - * level). The context is automatically reinitialized. - * - * @param cc the Keccak-224 context - * @param ub the extra bits - * @param n the number of extra bits (0 to 7) - * @param dst the destination buffer - */ -void sph_keccak224_addbits_and_close( - void *cc, unsigned ub, unsigned n, void *dst); - -/** - * Initialize a Keccak-256 context. This process performs no memory allocation. - * - * @param cc the Keccak-256 context (pointer to a - * sph_keccak256_context) - */ -void sph_keccak256_init(void *cc); - -/** - * Process some data bytes. It is acceptable that len is zero - * (in which case this function does nothing). - * - * @param cc the Keccak-256 context - * @param data the input data - * @param len the input data length (in bytes) - */ -void sph_keccak256(void *cc, const void *data, size_t len); - -/** - * Terminate the current Keccak-256 computation and output the result into - * the provided buffer. The destination buffer must be wide enough to - * accomodate the result (32 bytes). The context is automatically - * reinitialized. - * - * @param cc the Keccak-256 context - * @param dst the destination buffer - */ -void sph_keccak256_close(void *cc, void *dst); - -/** - * Add a few additional bits (0 to 7) to the current computation, then - * terminate it and output the result in the provided buffer, which must - * be wide enough to accomodate the result (32 bytes). If bit number i - * in ub has value 2^i, then the extra bits are those - * numbered 7 downto 8-n (this is the big-endian convention at the byte - * level). The context is automatically reinitialized. - * - * @param cc the Keccak-256 context - * @param ub the extra bits - * @param n the number of extra bits (0 to 7) - * @param dst the destination buffer - */ -void sph_keccak256_addbits_and_close( - void *cc, unsigned ub, unsigned n, void *dst); - -/** - * Initialize a Keccak-384 context. This process performs no memory allocation. - * - * @param cc the Keccak-384 context (pointer to a - * sph_keccak384_context) - */ -void sph_keccak384_init(void *cc); - -/** - * Process some data bytes. It is acceptable that len is zero - * (in which case this function does nothing). - * - * @param cc the Keccak-384 context - * @param data the input data - * @param len the input data length (in bytes) - */ -void sph_keccak384(void *cc, const void *data, size_t len); - -/** - * Terminate the current Keccak-384 computation and output the result into - * the provided buffer. The destination buffer must be wide enough to - * accomodate the result (48 bytes). The context is automatically - * reinitialized. - * - * @param cc the Keccak-384 context - * @param dst the destination buffer - */ -void sph_keccak384_close(void *cc, void *dst); - -/** - * Add a few additional bits (0 to 7) to the current computation, then - * terminate it and output the result in the provided buffer, which must - * be wide enough to accomodate the result (48 bytes). If bit number i - * in ub has value 2^i, then the extra bits are those - * numbered 7 downto 8-n (this is the big-endian convention at the byte - * level). The context is automatically reinitialized. - * - * @param cc the Keccak-384 context - * @param ub the extra bits - * @param n the number of extra bits (0 to 7) - * @param dst the destination buffer - */ -void sph_keccak384_addbits_and_close( - void *cc, unsigned ub, unsigned n, void *dst); - -/** - * Initialize a Keccak-512 context. This process performs no memory allocation. - * - * @param cc the Keccak-512 context (pointer to a - * sph_keccak512_context) - */ -void sph_keccak512_init(void *cc); - -/** - * Process some data bytes. It is acceptable that len is zero - * (in which case this function does nothing). - * - * @param cc the Keccak-512 context - * @param data the input data - * @param len the input data length (in bytes) - */ -void sph_keccak512(void *cc, const void *data, size_t len); - -/** - * Terminate the current Keccak-512 computation and output the result into - * the provided buffer. The destination buffer must be wide enough to - * accomodate the result (64 bytes). The context is automatically - * reinitialized. - * - * @param cc the Keccak-512 context - * @param dst the destination buffer - */ -void sph_keccak512_close(void *cc, void *dst); - -/** - * Add a few additional bits (0 to 7) to the current computation, then - * terminate it and output the result in the provided buffer, which must - * be wide enough to accomodate the result (64 bytes). If bit number i - * in ub has value 2^i, then the extra bits are those - * numbered 7 downto 8-n (this is the big-endian convention at the byte - * level). The context is automatically reinitialized. - * - * @param cc the Keccak-512 context - * @param ub the extra bits - * @param n the number of extra bits (0 to 7) - * @param dst the destination buffer - */ -void sph_keccak512_addbits_and_close( - void *cc, unsigned ub, unsigned n, void *dst); - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/src/crypto/sph_skein.h b/src/crypto/sph_skein.h deleted file mode 100644 index bddbc86fa5aa..000000000000 --- a/src/crypto/sph_skein.h +++ /dev/null @@ -1,298 +0,0 @@ -/* $Id: sph_skein.h 253 2011-06-07 18:33:10Z tp $ */ -/** - * Skein interface. The Skein specification defines three main - * functions, called Skein-256, Skein-512 and Skein-1024, which can be - * further parameterized with an output length. For the SHA-3 - * competition, Skein-512 is used for output sizes of 224, 256, 384 and - * 512 bits; this is what this code implements. Thus, we hereafter call - * Skein-224, Skein-256, Skein-384 and Skein-512 what the Skein - * specification defines as Skein-512-224, Skein-512-256, Skein-512-384 - * and Skein-512-512, respectively. - * - * ==========================(LICENSE BEGIN)============================ - * - * Copyright (c) 2007-2010 Projet RNRT SAPHIR - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY - * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, - * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE - * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - * ===========================(LICENSE END)============================= - * - * @file sph_skein.h - * @author Thomas Pornin - */ - -#ifndef SPH_SKEIN_H__ -#define SPH_SKEIN_H__ - -#ifdef __cplusplus -extern "C"{ -#endif - -#include -#include "sph_types.h" - -#if SPH_64 - -/** - * Output size (in bits) for Skein-224. - */ -#define SPH_SIZE_skein224 224 - -/** - * Output size (in bits) for Skein-256. - */ -#define SPH_SIZE_skein256 256 - -/** - * Output size (in bits) for Skein-384. - */ -#define SPH_SIZE_skein384 384 - -/** - * Output size (in bits) for Skein-512. - */ -#define SPH_SIZE_skein512 512 - -/** - * This structure is a context for Skein computations (with a 384- or - * 512-bit output): it contains the intermediate values and some data - * from the last entered block. Once a Skein computation has been - * performed, the context can be reused for another computation. - * - * The contents of this structure are private. A running Skein computation - * can be cloned by copying the context (e.g. with a simple - * memcpy()). - */ -typedef struct { -#ifndef DOXYGEN_IGNORE - unsigned char buf[64]; /* first field, for alignment */ - size_t ptr; - sph_u64 h0, h1, h2, h3, h4, h5, h6, h7; - sph_u64 bcount; -#endif -} sph_skein_big_context; - -/** - * Type for a Skein-224 context (identical to the common "big" context). - */ -typedef sph_skein_big_context sph_skein224_context; - -/** - * Type for a Skein-256 context (identical to the common "big" context). - */ -typedef sph_skein_big_context sph_skein256_context; - -/** - * Type for a Skein-384 context (identical to the common "big" context). - */ -typedef sph_skein_big_context sph_skein384_context; - -/** - * Type for a Skein-512 context (identical to the common "big" context). - */ -typedef sph_skein_big_context sph_skein512_context; - -/** - * Initialize a Skein-224 context. This process performs no memory allocation. - * - * @param cc the Skein-224 context (pointer to a - * sph_skein224_context) - */ -void sph_skein224_init(void *cc); - -/** - * Process some data bytes. It is acceptable that len is zero - * (in which case this function does nothing). - * - * @param cc the Skein-224 context - * @param data the input data - * @param len the input data length (in bytes) - */ -void sph_skein224(void *cc, const void *data, size_t len); - -/** - * Terminate the current Skein-224 computation and output the result into - * the provided buffer. The destination buffer must be wide enough to - * accomodate the result (28 bytes). The context is automatically - * reinitialized. - * - * @param cc the Skein-224 context - * @param dst the destination buffer - */ -void sph_skein224_close(void *cc, void *dst); - -/** - * Add a few additional bits (0 to 7) to the current computation, then - * terminate it and output the result in the provided buffer, which must - * be wide enough to accomodate the result (28 bytes). If bit number i - * in ub has value 2^i, then the extra bits are those - * numbered 7 downto 8-n (this is the big-endian convention at the byte - * level). The context is automatically reinitialized. - * - * @param cc the Skein-224 context - * @param ub the extra bits - * @param n the number of extra bits (0 to 7) - * @param dst the destination buffer - */ -void sph_skein224_addbits_and_close( - void *cc, unsigned ub, unsigned n, void *dst); - -/** - * Initialize a Skein-256 context. This process performs no memory allocation. - * - * @param cc the Skein-256 context (pointer to a - * sph_skein256_context) - */ -void sph_skein256_init(void *cc); - -/** - * Process some data bytes. It is acceptable that len is zero - * (in which case this function does nothing). - * - * @param cc the Skein-256 context - * @param data the input data - * @param len the input data length (in bytes) - */ -void sph_skein256(void *cc, const void *data, size_t len); - -/** - * Terminate the current Skein-256 computation and output the result into - * the provided buffer. The destination buffer must be wide enough to - * accomodate the result (32 bytes). The context is automatically - * reinitialized. - * - * @param cc the Skein-256 context - * @param dst the destination buffer - */ -void sph_skein256_close(void *cc, void *dst); - -/** - * Add a few additional bits (0 to 7) to the current computation, then - * terminate it and output the result in the provided buffer, which must - * be wide enough to accomodate the result (32 bytes). If bit number i - * in ub has value 2^i, then the extra bits are those - * numbered 7 downto 8-n (this is the big-endian convention at the byte - * level). The context is automatically reinitialized. - * - * @param cc the Skein-256 context - * @param ub the extra bits - * @param n the number of extra bits (0 to 7) - * @param dst the destination buffer - */ -void sph_skein256_addbits_and_close( - void *cc, unsigned ub, unsigned n, void *dst); - -/** - * Initialize a Skein-384 context. This process performs no memory allocation. - * - * @param cc the Skein-384 context (pointer to a - * sph_skein384_context) - */ -void sph_skein384_init(void *cc); - -/** - * Process some data bytes. It is acceptable that len is zero - * (in which case this function does nothing). - * - * @param cc the Skein-384 context - * @param data the input data - * @param len the input data length (in bytes) - */ -void sph_skein384(void *cc, const void *data, size_t len); - -/** - * Terminate the current Skein-384 computation and output the result into - * the provided buffer. The destination buffer must be wide enough to - * accomodate the result (48 bytes). The context is automatically - * reinitialized. - * - * @param cc the Skein-384 context - * @param dst the destination buffer - */ -void sph_skein384_close(void *cc, void *dst); - -/** - * Add a few additional bits (0 to 7) to the current computation, then - * terminate it and output the result in the provided buffer, which must - * be wide enough to accomodate the result (48 bytes). If bit number i - * in ub has value 2^i, then the extra bits are those - * numbered 7 downto 8-n (this is the big-endian convention at the byte - * level). The context is automatically reinitialized. - * - * @param cc the Skein-384 context - * @param ub the extra bits - * @param n the number of extra bits (0 to 7) - * @param dst the destination buffer - */ -void sph_skein384_addbits_and_close( - void *cc, unsigned ub, unsigned n, void *dst); - -/** - * Initialize a Skein-512 context. This process performs no memory allocation. - * - * @param cc the Skein-512 context (pointer to a - * sph_skein512_context) - */ -void sph_skein512_init(void *cc); - -/** - * Process some data bytes. It is acceptable that len is zero - * (in which case this function does nothing). - * - * @param cc the Skein-512 context - * @param data the input data - * @param len the input data length (in bytes) - */ -void sph_skein512(void *cc, const void *data, size_t len); - -/** - * Terminate the current Skein-512 computation and output the result into - * the provided buffer. The destination buffer must be wide enough to - * accomodate the result (64 bytes). The context is automatically - * reinitialized. - * - * @param cc the Skein-512 context - * @param dst the destination buffer - */ -void sph_skein512_close(void *cc, void *dst); - -/** - * Add a few additional bits (0 to 7) to the current computation, then - * terminate it and output the result in the provided buffer, which must - * be wide enough to accomodate the result (64 bytes). If bit number i - * in ub has value 2^i, then the extra bits are those - * numbered 7 downto 8-n (this is the big-endian convention at the byte - * level). The context is automatically reinitialized. - * - * @param cc the Skein-512 context - * @param ub the extra bits - * @param n the number of extra bits (0 to 7) - * @param dst the destination buffer - */ -void sph_skein512_addbits_and_close( - void *cc, unsigned ub, unsigned n, void *dst); - -#endif - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/src/crypto/sph_types.h b/src/crypto/sph_types.h deleted file mode 100644 index 7295b0b37097..000000000000 --- a/src/crypto/sph_types.h +++ /dev/null @@ -1,1976 +0,0 @@ -/* $Id: sph_types.h 260 2011-07-21 01:02:38Z tp $ */ -/** - * Basic type definitions. - * - * This header file defines the generic integer types that will be used - * for the implementation of hash functions; it also contains helper - * functions which encode and decode multi-byte integer values, using - * either little-endian or big-endian conventions. - * - * This file contains a compile-time test on the size of a byte - * (the unsigned char C type). If bytes are not octets, - * i.e. if they do not have a size of exactly 8 bits, then compilation - * is aborted. Architectures where bytes are not octets are relatively - * rare, even in the embedded devices market. We forbid non-octet bytes - * because there is no clear convention on how octet streams are encoded - * on such systems. - * - * ==========================(LICENSE BEGIN)============================ - * - * Copyright (c) 2007-2010 Projet RNRT SAPHIR - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY - * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, - * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE - * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - * ===========================(LICENSE END)============================= - * - * @file sph_types.h - * @author Thomas Pornin - */ - -#ifndef SPH_TYPES_H__ -#define SPH_TYPES_H__ - -#include - -/* - * All our I/O functions are defined over octet streams. We do not know - * how to handle input data if bytes are not octets. - */ -#if CHAR_BIT != 8 -#error This code requires 8-bit bytes -#endif - -/* ============= BEGIN documentation block for Doxygen ============ */ - -#ifdef DOXYGEN_IGNORE - -/** @mainpage sphlib C code documentation - * - * @section overview Overview - * - * sphlib is a library which contains implementations of - * various cryptographic hash functions. These pages have been generated - * with doxygen and - * document the API for the C implementations. - * - * The API is described in appropriate header files, which are available - * in the "Files" section. Each hash function family has its own header, - * whose name begins with "sph_" and contains the family - * name. For instance, the API for the RIPEMD hash functions is available - * in the header file sph_ripemd.h. - * - * @section principles API structure and conventions - * - * @subsection io Input/output conventions - * - * In all generality, hash functions operate over strings of bits. - * Individual bits are rarely encountered in C programming or actual - * communication protocols; most protocols converge on the ubiquitous - * "octet" which is a group of eight bits. Data is thus expressed as a - * stream of octets. The C programming language contains the notion of a - * "byte", which is a data unit managed under the type "unsigned - * char". The C standard prescribes that a byte should hold at - * least eight bits, but possibly more. Most modern architectures, even - * in the embedded world, feature eight-bit bytes, i.e. map bytes to - * octets. - * - * Nevertheless, for some of the implemented hash functions, an extra - * API has been added, which allows the input of arbitrary sequences of - * bits: when the computation is about to be closed, 1 to 7 extra bits - * can be added. The functions for which this API is implemented include - * the SHA-2 functions and all SHA-3 candidates. - * - * sphlib defines hash function which may hash octet streams, - * i.e. streams of bits where the number of bits is a multiple of eight. - * The data input functions in the sphlib API expect data - * as anonymous pointers ("const void *") with a length - * (of type "size_t") which gives the input data chunk length - * in bytes. A byte is assumed to be an octet; the sph_types.h - * header contains a compile-time test which prevents compilation on - * architectures where this property is not met. - * - * The hash function output is also converted into bytes. All currently - * implemented hash functions have an output width which is a multiple of - * eight, and this is likely to remain true for new designs. - * - * Most hash functions internally convert input data into 32-bit of 64-bit - * words, using either little-endian or big-endian conversion. The hash - * output also often consists of such words, which are encoded into output - * bytes with a similar endianness convention. Some hash functions have - * been only loosely specified on that subject; when necessary, - * sphlib has been tested against published "reference" - * implementations in order to use the same conventions. - * - * @subsection shortname Function short name - * - * Each implemented hash function has a "short name" which is used - * internally to derive the identifiers for the functions and context - * structures which the function uses. For instance, MD5 has the short - * name "md5". Short names are listed in the next section, - * for the implemented hash functions. In subsequent sections, the - * short name will be assumed to be "XXX": replace with the - * actual hash function name to get the C identifier. - * - * Note: some functions within the same family share the same core - * elements, such as update function or context structure. Correspondingly, - * some of the defined types or functions may actually be macros which - * transparently evaluate to another type or function name. - * - * @subsection context Context structure - * - * Each implemented hash fonction has its own context structure, available - * under the type name "sph_XXX_context" for the hash function - * with short name "XXX". This structure holds all needed - * state for a running hash computation. - * - * The contents of these structures are meant to be opaque, and private - * to the implementation. However, these contents are specified in the - * header files so that application code which uses sphlib - * may access the size of those structures. - * - * The caller is responsible for allocating the context structure, - * whether by dynamic allocation (malloc() or equivalent), - * static allocation (a global permanent variable), as an automatic - * variable ("on the stack"), or by any other mean which ensures proper - * structure alignment. sphlib code performs no dynamic - * allocation by itself. - * - * The context must be initialized before use, using the - * sph_XXX_init() function. This function sets the context - * state to proper initial values for hashing. - * - * Since all state data is contained within the context structure, - * sphlib is thread-safe and reentrant: several hash - * computations may be performed in parallel, provided that they do not - * operate on the same context. Moreover, a running computation can be - * cloned by copying the context (with a simple memcpy()): - * the context and its clone are then independant and may be updated - * with new data and/or closed without interfering with each other. - * Similarly, a context structure can be moved in memory at will: - * context structures contain no pointer, in particular no pointer to - * themselves. - * - * @subsection dataio Data input - * - * Hashed data is input with the sph_XXX() fonction, which - * takes as parameters a pointer to the context, a pointer to the data - * to hash, and the number of data bytes to hash. The context is updated - * with the new data. - * - * Data can be input in one or several calls, with arbitrary input lengths. - * However, it is best, performance wise, to input data by relatively big - * chunks (say a few kilobytes), because this allows sphlib to - * optimize things and avoid internal copying. - * - * When all data has been input, the context can be closed with - * sph_XXX_close(). The hash output is computed and written - * into the provided buffer. The caller must take care to provide a - * buffer of appropriate length; e.g., when using SHA-1, the output is - * a 20-byte word, therefore the output buffer must be at least 20-byte - * long. - * - * For some hash functions, the sph_XXX_addbits_and_close() - * function can be used instead of sph_XXX_close(). This - * function can take a few extra bits to be added at - * the end of the input message. This allows hashing messages with a - * bit length which is not a multiple of 8. The extra bits are provided - * as an unsigned integer value, and a bit count. The bit count must be - * between 0 and 7, inclusive. The extra bits are provided as bits 7 to - * 0 (bits of numerical value 128, 64, 32... downto 0), in that order. - * For instance, to add three bits of value 1, 1 and 0, the unsigned - * integer will have value 192 (1*128 + 1*64 + 0*32) and the bit count - * will be 3. - * - * The SPH_SIZE_XXX macro is defined for each hash function; - * it evaluates to the function output size, expressed in bits. For instance, - * SPH_SIZE_sha1 evaluates to 160. - * - * When closed, the context is automatically reinitialized and can be - * immediately used for another computation. It is not necessary to call - * sph_XXX_init() after a close. Note that - * sph_XXX_init() can still be called to "reset" a context, - * i.e. forget previously input data, and get back to the initial state. - * - * @subsection alignment Data alignment - * - * "Alignment" is a property of data, which is said to be "properly - * aligned" when its emplacement in memory is such that the data can - * be optimally read by full words. This depends on the type of access; - * basically, some hash functions will read data by 32-bit or 64-bit - * words. sphlib does not mandate such alignment for input - * data, but using aligned data can substantially improve performance. - * - * As a rule, it is best to input data by chunks whose length (in bytes) - * is a multiple of eight, and which begins at "generally aligned" - * addresses, such as the base address returned by a call to - * malloc(). - * - * @section functions Implemented functions - * - * We give here the list of implemented functions. They are grouped by - * family; to each family corresponds a specific header file. Each - * individual function has its associated "short name". Please refer to - * the documentation for that header file to get details on the hash - * function denomination and provenance. - * - * Note: the functions marked with a '(64)' in the list below are - * available only if the C compiler provides an integer type of length - * 64 bits or more. Such a type is mandatory in the latest C standard - * (ISO 9899:1999, aka "C99") and is present in several older compilers - * as well, so chances are that such a type is available. - * - * - HAVAL family: file sph_haval.h - * - HAVAL-128/3 (128-bit, 3 passes): short name: haval128_3 - * - HAVAL-128/4 (128-bit, 4 passes): short name: haval128_4 - * - HAVAL-128/5 (128-bit, 5 passes): short name: haval128_5 - * - HAVAL-160/3 (160-bit, 3 passes): short name: haval160_3 - * - HAVAL-160/4 (160-bit, 4 passes): short name: haval160_4 - * - HAVAL-160/5 (160-bit, 5 passes): short name: haval160_5 - * - HAVAL-192/3 (192-bit, 3 passes): short name: haval192_3 - * - HAVAL-192/4 (192-bit, 4 passes): short name: haval192_4 - * - HAVAL-192/5 (192-bit, 5 passes): short name: haval192_5 - * - HAVAL-224/3 (224-bit, 3 passes): short name: haval224_3 - * - HAVAL-224/4 (224-bit, 4 passes): short name: haval224_4 - * - HAVAL-224/5 (224-bit, 5 passes): short name: haval224_5 - * - HAVAL-256/3 (256-bit, 3 passes): short name: haval256_3 - * - HAVAL-256/4 (256-bit, 4 passes): short name: haval256_4 - * - HAVAL-256/5 (256-bit, 5 passes): short name: haval256_5 - * - MD2: file sph_md2.h, short name: md2 - * - MD4: file sph_md4.h, short name: md4 - * - MD5: file sph_md5.h, short name: md5 - * - PANAMA: file sph_panama.h, short name: panama - * - RadioGatun family: file sph_radiogatun.h - * - RadioGatun[32]: short name: radiogatun32 - * - RadioGatun[64]: short name: radiogatun64 (64) - * - RIPEMD family: file sph_ripemd.h - * - RIPEMD: short name: ripemd - * - RIPEMD-128: short name: ripemd128 - * - RIPEMD-160: short name: ripemd160 - * - SHA-0: file sph_sha0.h, short name: sha0 - * - SHA-1: file sph_sha1.h, short name: sha1 - * - SHA-2 family, 32-bit hashes: file sph_sha2.h - * - SHA-224: short name: sha224 - * - SHA-256: short name: sha256 - * - SHA-384: short name: sha384 (64) - * - SHA-512: short name: sha512 (64) - * - Tiger family: file sph_tiger.h - * - Tiger: short name: tiger (64) - * - Tiger2: short name: tiger2 (64) - * - WHIRLPOOL family: file sph_whirlpool.h - * - WHIRLPOOL-0: short name: whirlpool0 (64) - * - WHIRLPOOL-1: short name: whirlpool1 (64) - * - WHIRLPOOL: short name: whirlpool (64) - * - * The fourteen second-round SHA-3 candidates are also implemented; - * when applicable, the implementations follow the "final" specifications - * as published for the third round of the SHA-3 competition (BLAKE, - * Groestl, JH, Keccak and Skein have been tweaked for third round). - * - * - BLAKE family: file sph_blake.h - * - BLAKE-224: short name: blake224 - * - BLAKE-256: short name: blake256 - * - BLAKE-384: short name: blake384 - * - BLAKE-512: short name: blake512 - * - BMW (Blue Midnight Wish) family: file sph_bmw.h - * - BMW-224: short name: bmw224 - * - BMW-256: short name: bmw256 - * - BMW-384: short name: bmw384 (64) - * - BMW-512: short name: bmw512 (64) - * - CubeHash family: file sph_cubehash.h (specified as - * CubeHash16/32 in the CubeHash specification) - * - CubeHash-224: short name: cubehash224 - * - CubeHash-256: short name: cubehash256 - * - CubeHash-384: short name: cubehash384 - * - CubeHash-512: short name: cubehash512 - * - ECHO family: file sph_echo.h - * - ECHO-224: short name: echo224 - * - ECHO-256: short name: echo256 - * - ECHO-384: short name: echo384 - * - ECHO-512: short name: echo512 - * - Fugue family: file sph_fugue.h - * - Fugue-224: short name: fugue224 - * - Fugue-256: short name: fugue256 - * - Fugue-384: short name: fugue384 - * - Fugue-512: short name: fugue512 - * - Groestl family: file sph_groestl.h - * - Groestl-224: short name: groestl224 - * - Groestl-256: short name: groestl256 - * - Groestl-384: short name: groestl384 - * - Groestl-512: short name: groestl512 - * - Hamsi family: file sph_hamsi.h - * - Hamsi-224: short name: hamsi224 - * - Hamsi-256: short name: hamsi256 - * - Hamsi-384: short name: hamsi384 - * - Hamsi-512: short name: hamsi512 - * - JH family: file sph_jh.h - * - JH-224: short name: jh224 - * - JH-256: short name: jh256 - * - JH-384: short name: jh384 - * - JH-512: short name: jh512 - * - Keccak family: file sph_keccak.h - * - Keccak-224: short name: keccak224 - * - Keccak-256: short name: keccak256 - * - Keccak-384: short name: keccak384 - * - Keccak-512: short name: keccak512 - * - Luffa family: file sph_luffa.h - * - Luffa-224: short name: luffa224 - * - Luffa-256: short name: luffa256 - * - Luffa-384: short name: luffa384 - * - Luffa-512: short name: luffa512 - * - Shabal family: file sph_shabal.h - * - Shabal-192: short name: shabal192 - * - Shabal-224: short name: shabal224 - * - Shabal-256: short name: shabal256 - * - Shabal-384: short name: shabal384 - * - Shabal-512: short name: shabal512 - * - SHAvite-3 family: file sph_shavite.h - * - SHAvite-224 (nominally "SHAvite-3 with 224-bit output"): - * short name: shabal224 - * - SHAvite-256 (nominally "SHAvite-3 with 256-bit output"): - * short name: shabal256 - * - SHAvite-384 (nominally "SHAvite-3 with 384-bit output"): - * short name: shabal384 - * - SHAvite-512 (nominally "SHAvite-3 with 512-bit output"): - * short name: shabal512 - * - SIMD family: file sph_simd.h - * - SIMD-224: short name: simd224 - * - SIMD-256: short name: simd256 - * - SIMD-384: short name: simd384 - * - SIMD-512: short name: simd512 - * - Skein family: file sph_skein.h - * - Skein-224 (nominally specified as Skein-512-224): short name: - * skein224 (64) - * - Skein-256 (nominally specified as Skein-512-256): short name: - * skein256 (64) - * - Skein-384 (nominally specified as Skein-512-384): short name: - * skein384 (64) - * - Skein-512 (nominally specified as Skein-512-512): short name: - * skein512 (64) - * - * For the second-round SHA-3 candidates, the functions are as specified - * for round 2, i.e. with the "tweaks" that some candidates added - * between round 1 and round 2. Also, some of the submitted packages for - * round 2 contained errors, in the specification, reference code, or - * both. sphlib implements the corrected versions. - */ - -/** @hideinitializer - * Unsigned integer type whose length is at least 32 bits; on most - * architectures, it will have a width of exactly 32 bits. Unsigned C - * types implement arithmetics modulo a power of 2; use the - * SPH_T32() macro to ensure that the value is truncated - * to exactly 32 bits. Unless otherwise specified, all macros and - * functions which accept sph_u32 values assume that these - * values fit on 32 bits, i.e. do not exceed 2^32-1, even on architectures - * where sph_u32 is larger than that. - */ -typedef __arch_dependant__ sph_u32; - -/** @hideinitializer - * Signed integer type corresponding to sph_u32; it has - * width 32 bits or more. - */ -typedef __arch_dependant__ sph_s32; - -/** @hideinitializer - * Unsigned integer type whose length is at least 64 bits; on most - * architectures which feature such a type, it will have a width of - * exactly 64 bits. C99-compliant platform will have this type; it - * is also defined when the GNU compiler (gcc) is used, and on - * platforms where unsigned long is large enough. If this - * type is not available, then some hash functions which depends on - * a 64-bit type will not be available (most notably SHA-384, SHA-512, - * Tiger and WHIRLPOOL). - */ -typedef __arch_dependant__ sph_u64; - -/** @hideinitializer - * Signed integer type corresponding to sph_u64; it has - * width 64 bits or more. - */ -typedef __arch_dependant__ sph_s64; - -/** - * This macro expands the token x into a suitable - * constant expression of type sph_u32. Depending on - * how this type is defined, a suffix such as UL may - * be appended to the argument. - * - * @param x the token to expand into a suitable constant expression - */ -#define SPH_C32(x) - -/** - * Truncate a 32-bit value to exactly 32 bits. On most systems, this is - * a no-op, recognized as such by the compiler. - * - * @param x the value to truncate (of type sph_u32) - */ -#define SPH_T32(x) - -/** - * Rotate a 32-bit value by a number of bits to the left. The rotate - * count must reside between 1 and 31. This macro assumes that its - * first argument fits in 32 bits (no extra bit allowed on machines where - * sph_u32 is wider); both arguments may be evaluated - * several times. - * - * @param x the value to rotate (of type sph_u32) - * @param n the rotation count (between 1 and 31, inclusive) - */ -#define SPH_ROTL32(x, n) - -/** - * Rotate a 32-bit value by a number of bits to the left. The rotate - * count must reside between 1 and 31. This macro assumes that its - * first argument fits in 32 bits (no extra bit allowed on machines where - * sph_u32 is wider); both arguments may be evaluated - * several times. - * - * @param x the value to rotate (of type sph_u32) - * @param n the rotation count (between 1 and 31, inclusive) - */ -#define SPH_ROTR32(x, n) - -/** - * This macro is defined on systems for which a 64-bit type has been - * detected, and is used for sph_u64. - */ -#define SPH_64 - -/** - * This macro is defined on systems for the "native" integer size is - * 64 bits (64-bit values fit in one register). - */ -#define SPH_64_TRUE - -/** - * This macro expands the token x into a suitable - * constant expression of type sph_u64. Depending on - * how this type is defined, a suffix such as ULL may - * be appended to the argument. This macro is defined only if a - * 64-bit type was detected and used for sph_u64. - * - * @param x the token to expand into a suitable constant expression - */ -#define SPH_C64(x) - -/** - * Truncate a 64-bit value to exactly 64 bits. On most systems, this is - * a no-op, recognized as such by the compiler. This macro is defined only - * if a 64-bit type was detected and used for sph_u64. - * - * @param x the value to truncate (of type sph_u64) - */ -#define SPH_T64(x) - -/** - * Rotate a 64-bit value by a number of bits to the left. The rotate - * count must reside between 1 and 63. This macro assumes that its - * first argument fits in 64 bits (no extra bit allowed on machines where - * sph_u64 is wider); both arguments may be evaluated - * several times. This macro is defined only if a 64-bit type was detected - * and used for sph_u64. - * - * @param x the value to rotate (of type sph_u64) - * @param n the rotation count (between 1 and 63, inclusive) - */ -#define SPH_ROTL64(x, n) - -/** - * Rotate a 64-bit value by a number of bits to the left. The rotate - * count must reside between 1 and 63. This macro assumes that its - * first argument fits in 64 bits (no extra bit allowed on machines where - * sph_u64 is wider); both arguments may be evaluated - * several times. This macro is defined only if a 64-bit type was detected - * and used for sph_u64. - * - * @param x the value to rotate (of type sph_u64) - * @param n the rotation count (between 1 and 63, inclusive) - */ -#define SPH_ROTR64(x, n) - -/** - * This macro evaluates to inline or an equivalent construction, - * if available on the compilation platform, or to nothing otherwise. This - * is used to declare inline functions, for which the compiler should - * endeavour to include the code directly in the caller. Inline functions - * are typically defined in header files as replacement for macros. - */ -#define SPH_INLINE - -/** - * This macro is defined if the platform has been detected as using - * little-endian convention. This implies that the sph_u32 - * type (and the sph_u64 type also, if it is defined) has - * an exact width (i.e. exactly 32-bit, respectively 64-bit). - */ -#define SPH_LITTLE_ENDIAN - -/** - * This macro is defined if the platform has been detected as using - * big-endian convention. This implies that the sph_u32 - * type (and the sph_u64 type also, if it is defined) has - * an exact width (i.e. exactly 32-bit, respectively 64-bit). - */ -#define SPH_BIG_ENDIAN - -/** - * This macro is defined if 32-bit words (and 64-bit words, if defined) - * can be read from and written to memory efficiently in little-endian - * convention. This is the case for little-endian platforms, and also - * for the big-endian platforms which have special little-endian access - * opcodes (e.g. Ultrasparc). - */ -#define SPH_LITTLE_FAST - -/** - * This macro is defined if 32-bit words (and 64-bit words, if defined) - * can be read from and written to memory efficiently in big-endian - * convention. This is the case for little-endian platforms, and also - * for the little-endian platforms which have special big-endian access - * opcodes. - */ -#define SPH_BIG_FAST - -/** - * On some platforms, this macro is defined to an unsigned integer type - * into which pointer values may be cast. The resulting value can then - * be tested for being a multiple of 2, 4 or 8, indicating an aligned - * pointer for, respectively, 16-bit, 32-bit or 64-bit memory accesses. - */ -#define SPH_UPTR - -/** - * When defined, this macro indicates that unaligned memory accesses - * are possible with only a minor penalty, and thus should be prefered - * over strategies which first copy data to an aligned buffer. - */ -#define SPH_UNALIGNED - -/** - * Byte-swap a 32-bit word (i.e. 0x12345678 becomes - * 0x78563412). This is an inline function which resorts - * to inline assembly on some platforms, for better performance. - * - * @param x the 32-bit value to byte-swap - * @return the byte-swapped value - */ -static inline sph_u32 sph_bswap32(sph_u32 x); - -/** - * Byte-swap a 64-bit word. This is an inline function which resorts - * to inline assembly on some platforms, for better performance. This - * function is defined only if a suitable 64-bit type was found for - * sph_u64 - * - * @param x the 64-bit value to byte-swap - * @return the byte-swapped value - */ -static inline sph_u64 sph_bswap64(sph_u64 x); - -/** - * Decode a 16-bit unsigned value from memory, in little-endian convention - * (least significant byte comes first). - * - * @param src the source address - * @return the decoded value - */ -static inline unsigned sph_dec16le(const void *src); - -/** - * Encode a 16-bit unsigned value into memory, in little-endian convention - * (least significant byte comes first). - * - * @param dst the destination buffer - * @param val the value to encode - */ -static inline void sph_enc16le(void *dst, unsigned val); - -/** - * Decode a 16-bit unsigned value from memory, in big-endian convention - * (most significant byte comes first). - * - * @param src the source address - * @return the decoded value - */ -static inline unsigned sph_dec16be(const void *src); - -/** - * Encode a 16-bit unsigned value into memory, in big-endian convention - * (most significant byte comes first). - * - * @param dst the destination buffer - * @param val the value to encode - */ -static inline void sph_enc16be(void *dst, unsigned val); - -/** - * Decode a 32-bit unsigned value from memory, in little-endian convention - * (least significant byte comes first). - * - * @param src the source address - * @return the decoded value - */ -static inline sph_u32 sph_dec32le(const void *src); - -/** - * Decode a 32-bit unsigned value from memory, in little-endian convention - * (least significant byte comes first). This function assumes that the - * source address is suitably aligned for a direct access, if the platform - * supports such things; it can thus be marginally faster than the generic - * sph_dec32le() function. - * - * @param src the source address - * @return the decoded value - */ -static inline sph_u32 sph_dec32le_aligned(const void *src); - -/** - * Encode a 32-bit unsigned value into memory, in little-endian convention - * (least significant byte comes first). - * - * @param dst the destination buffer - * @param val the value to encode - */ -static inline void sph_enc32le(void *dst, sph_u32 val); - -/** - * Encode a 32-bit unsigned value into memory, in little-endian convention - * (least significant byte comes first). This function assumes that the - * destination address is suitably aligned for a direct access, if the - * platform supports such things; it can thus be marginally faster than - * the generic sph_enc32le() function. - * - * @param dst the destination buffer - * @param val the value to encode - */ -static inline void sph_enc32le_aligned(void *dst, sph_u32 val); - -/** - * Decode a 32-bit unsigned value from memory, in big-endian convention - * (most significant byte comes first). - * - * @param src the source address - * @return the decoded value - */ -static inline sph_u32 sph_dec32be(const void *src); - -/** - * Decode a 32-bit unsigned value from memory, in big-endian convention - * (most significant byte comes first). This function assumes that the - * source address is suitably aligned for a direct access, if the platform - * supports such things; it can thus be marginally faster than the generic - * sph_dec32be() function. - * - * @param src the source address - * @return the decoded value - */ -static inline sph_u32 sph_dec32be_aligned(const void *src); - -/** - * Encode a 32-bit unsigned value into memory, in big-endian convention - * (most significant byte comes first). - * - * @param dst the destination buffer - * @param val the value to encode - */ -static inline void sph_enc32be(void *dst, sph_u32 val); - -/** - * Encode a 32-bit unsigned value into memory, in big-endian convention - * (most significant byte comes first). This function assumes that the - * destination address is suitably aligned for a direct access, if the - * platform supports such things; it can thus be marginally faster than - * the generic sph_enc32be() function. - * - * @param dst the destination buffer - * @param val the value to encode - */ -static inline void sph_enc32be_aligned(void *dst, sph_u32 val); - -/** - * Decode a 64-bit unsigned value from memory, in little-endian convention - * (least significant byte comes first). This function is defined only - * if a suitable 64-bit type was detected and used for sph_u64. - * - * @param src the source address - * @return the decoded value - */ -static inline sph_u64 sph_dec64le(const void *src); - -/** - * Decode a 64-bit unsigned value from memory, in little-endian convention - * (least significant byte comes first). This function assumes that the - * source address is suitably aligned for a direct access, if the platform - * supports such things; it can thus be marginally faster than the generic - * sph_dec64le() function. This function is defined only - * if a suitable 64-bit type was detected and used for sph_u64. - * - * @param src the source address - * @return the decoded value - */ -static inline sph_u64 sph_dec64le_aligned(const void *src); - -/** - * Encode a 64-bit unsigned value into memory, in little-endian convention - * (least significant byte comes first). This function is defined only - * if a suitable 64-bit type was detected and used for sph_u64. - * - * @param dst the destination buffer - * @param val the value to encode - */ -static inline void sph_enc64le(void *dst, sph_u64 val); - -/** - * Encode a 64-bit unsigned value into memory, in little-endian convention - * (least significant byte comes first). This function assumes that the - * destination address is suitably aligned for a direct access, if the - * platform supports such things; it can thus be marginally faster than - * the generic sph_enc64le() function. This function is defined - * only if a suitable 64-bit type was detected and used for - * sph_u64. - * - * @param dst the destination buffer - * @param val the value to encode - */ -static inline void sph_enc64le_aligned(void *dst, sph_u64 val); - -/** - * Decode a 64-bit unsigned value from memory, in big-endian convention - * (most significant byte comes first). This function is defined only - * if a suitable 64-bit type was detected and used for sph_u64. - * - * @param src the source address - * @return the decoded value - */ -static inline sph_u64 sph_dec64be(const void *src); - -/** - * Decode a 64-bit unsigned value from memory, in big-endian convention - * (most significant byte comes first). This function assumes that the - * source address is suitably aligned for a direct access, if the platform - * supports such things; it can thus be marginally faster than the generic - * sph_dec64be() function. This function is defined only - * if a suitable 64-bit type was detected and used for sph_u64. - * - * @param src the source address - * @return the decoded value - */ -static inline sph_u64 sph_dec64be_aligned(const void *src); - -/** - * Encode a 64-bit unsigned value into memory, in big-endian convention - * (most significant byte comes first). This function is defined only - * if a suitable 64-bit type was detected and used for sph_u64. - * - * @param dst the destination buffer - * @param val the value to encode - */ -static inline void sph_enc64be(void *dst, sph_u64 val); - -/** - * Encode a 64-bit unsigned value into memory, in big-endian convention - * (most significant byte comes first). This function assumes that the - * destination address is suitably aligned for a direct access, if the - * platform supports such things; it can thus be marginally faster than - * the generic sph_enc64be() function. This function is defined - * only if a suitable 64-bit type was detected and used for - * sph_u64. - * - * @param dst the destination buffer - * @param val the value to encode - */ -static inline void sph_enc64be_aligned(void *dst, sph_u64 val); - -#endif - -/* ============== END documentation block for Doxygen ============= */ - -#ifndef DOXYGEN_IGNORE - -/* - * We want to define the types "sph_u32" and "sph_u64" which hold - * unsigned values of at least, respectively, 32 and 64 bits. These - * tests should select appropriate types for most platforms. The - * macro "SPH_64" is defined if the 64-bit is supported. - */ - -#undef SPH_64 -#undef SPH_64_TRUE - -#if defined __STDC__ && __STDC_VERSION__ >= 199901L - -/* - * On C99 implementations, we can use to get an exact 64-bit - * type, if any, or otherwise use a wider type (which must exist, for - * C99 conformance). - */ - -#include - -#ifdef UINT32_MAX -typedef uint32_t sph_u32; -typedef int32_t sph_s32; -#else -typedef uint_fast32_t sph_u32; -typedef int_fast32_t sph_s32; -#endif -#if !SPH_NO_64 -#ifdef UINT64_MAX -typedef uint64_t sph_u64; -typedef int64_t sph_s64; -#else -typedef uint_fast64_t sph_u64; -typedef int_fast64_t sph_s64; -#endif -#endif - -#define SPH_C32(x) ((sph_u32)(x)) -#if !SPH_NO_64 -#define SPH_C64(x) ((sph_u64)(x)) -#define SPH_64 1 -#endif - -#else - -/* - * On non-C99 systems, we use "unsigned int" if it is wide enough, - * "unsigned long" otherwise. This supports all "reasonable" architectures. - * We have to be cautious: pre-C99 preprocessors handle constants - * differently in '#if' expressions. Hence the shifts to test UINT_MAX. - */ - -#if ((UINT_MAX >> 11) >> 11) >= 0x3FF - -typedef unsigned int sph_u32; -typedef int sph_s32; - -#define SPH_C32(x) ((sph_u32)(x ## U)) - -#else - -typedef unsigned long sph_u32; -typedef long sph_s32; - -#define SPH_C32(x) ((sph_u32)(x ## UL)) - -#endif - -#if !SPH_NO_64 - -/* - * We want a 64-bit type. We use "unsigned long" if it is wide enough (as - * is common on 64-bit architectures such as AMD64, Alpha or Sparcv9), - * "unsigned long long" otherwise, if available. We use ULLONG_MAX to - * test whether "unsigned long long" is available; we also know that - * gcc features this type, even if the libc header do not know it. - */ - -#if ((ULONG_MAX >> 31) >> 31) >= 3 - -typedef unsigned long sph_u64; -typedef long sph_s64; - -#define SPH_C64(x) ((sph_u64)(x ## UL)) - -#define SPH_64 1 - -#elif ((ULLONG_MAX >> 31) >> 31) >= 3 || defined __GNUC__ - -typedef unsigned long long sph_u64; -typedef long long sph_s64; - -#define SPH_C64(x) ((sph_u64)(x ## ULL)) - -#define SPH_64 1 - -#else - -/* - * No 64-bit type... - */ - -#endif - -#endif - -#endif - -/* - * If the "unsigned long" type has length 64 bits or more, then this is - * a "true" 64-bit architectures. This is also true with Visual C on - * amd64, even though the "long" type is limited to 32 bits. - */ -#if SPH_64 && (((ULONG_MAX >> 31) >> 31) >= 3 || defined _M_X64) -#define SPH_64_TRUE 1 -#endif - -/* - * Implementation note: some processors have specific opcodes to perform - * a rotation. Recent versions of gcc recognize the expression above and - * use the relevant opcodes, when appropriate. - */ - -#define SPH_T32(x) ((x) & SPH_C32(0xFFFFFFFF)) -#define SPH_ROTL32(x, n) SPH_T32(((x) << (n)) | ((x) >> (32 - (n)))) -#define SPH_ROTR32(x, n) SPH_ROTL32(x, (32 - (n))) - -#if SPH_64 - -#define SPH_T64(x) ((x) & SPH_C64(0xFFFFFFFFFFFFFFFF)) -#define SPH_ROTL64(x, n) SPH_T64(((x) << (n)) | ((x) >> (64 - (n)))) -#define SPH_ROTR64(x, n) SPH_ROTL64(x, (64 - (n))) - -#endif - -#ifndef DOXYGEN_IGNORE -/* - * Define SPH_INLINE to be an "inline" qualifier, if available. We define - * some small macro-like functions which benefit greatly from being inlined. - */ -#if (defined __STDC__ && __STDC_VERSION__ >= 199901L) || defined __GNUC__ -#define SPH_INLINE inline -#elif defined _MSC_VER -#define SPH_INLINE __inline -#else -#define SPH_INLINE -#endif -#endif - -/* - * We define some macros which qualify the architecture. These macros - * may be explicit set externally (e.g. as compiler parameters). The - * code below sets those macros if they are not already defined. - * - * Most macros are boolean, thus evaluate to either zero or non-zero. - * The SPH_UPTR macro is special, in that it evaluates to a C type, - * or is not defined. - * - * SPH_UPTR if defined: unsigned type to cast pointers into - * - * SPH_UNALIGNED non-zero if unaligned accesses are efficient - * SPH_LITTLE_ENDIAN non-zero if architecture is known to be little-endian - * SPH_BIG_ENDIAN non-zero if architecture is known to be big-endian - * SPH_LITTLE_FAST non-zero if little-endian decoding is fast - * SPH_BIG_FAST non-zero if big-endian decoding is fast - * - * If SPH_UPTR is defined, then encoding and decoding of 32-bit and 64-bit - * values will try to be "smart". Either SPH_LITTLE_ENDIAN or SPH_BIG_ENDIAN - * _must_ be non-zero in those situations. The 32-bit and 64-bit types - * _must_ also have an exact width. - * - * SPH_SPARCV9_GCC_32 UltraSPARC-compatible with gcc, 32-bit mode - * SPH_SPARCV9_GCC_64 UltraSPARC-compatible with gcc, 64-bit mode - * SPH_SPARCV9_GCC UltraSPARC-compatible with gcc - * SPH_I386_GCC x86-compatible (32-bit) with gcc - * SPH_I386_MSVC x86-compatible (32-bit) with Microsoft Visual C - * SPH_AMD64_GCC x86-compatible (64-bit) with gcc - * SPH_AMD64_MSVC x86-compatible (64-bit) with Microsoft Visual C - * SPH_PPC32_GCC PowerPC, 32-bit, with gcc - * SPH_PPC64_GCC PowerPC, 64-bit, with gcc - * - * TODO: enhance automatic detection, for more architectures and compilers. - * Endianness is the most important. SPH_UNALIGNED and SPH_UPTR help with - * some very fast functions (e.g. MD4) when using unaligned input data. - * The CPU-specific-with-GCC macros are useful only for inline assembly, - * normally restrained to this header file. - */ - -/* - * 32-bit x86, aka "i386 compatible". - */ -#if defined __i386__ || defined _M_IX86 - -#define SPH_DETECT_UNALIGNED 1 -#define SPH_DETECT_LITTLE_ENDIAN 1 -#define SPH_DETECT_UPTR sph_u32 -#ifdef __GNUC__ -#define SPH_DETECT_I386_GCC 1 -#endif -#ifdef _MSC_VER -#define SPH_DETECT_I386_MSVC 1 -#endif - -/* - * 64-bit x86, hereafter known as "amd64". - */ -#elif defined __x86_64 || defined _M_X64 - -#define SPH_DETECT_UNALIGNED 1 -#define SPH_DETECT_LITTLE_ENDIAN 1 -#define SPH_DETECT_UPTR sph_u64 -#ifdef __GNUC__ -#define SPH_DETECT_AMD64_GCC 1 -#endif -#ifdef _MSC_VER -#define SPH_DETECT_AMD64_MSVC 1 -#endif - -/* - * 64-bit Sparc architecture (implies v9). - */ -#elif ((defined __sparc__ || defined __sparc) && defined __arch64__) \ - || defined __sparcv9 - -#define SPH_DETECT_BIG_ENDIAN 1 -#define SPH_DETECT_UPTR sph_u64 -#ifdef __GNUC__ -#define SPH_DETECT_SPARCV9_GCC_64 1 -#define SPH_DETECT_LITTLE_FAST 1 -#endif - -/* - * 32-bit Sparc. - */ -#elif (defined __sparc__ || defined __sparc) \ - && !(defined __sparcv9 || defined __arch64__) - -#define SPH_DETECT_BIG_ENDIAN 1 -#define SPH_DETECT_UPTR sph_u32 -#if defined __GNUC__ && defined __sparc_v9__ -#define SPH_DETECT_SPARCV9_GCC_32 1 -#define SPH_DETECT_LITTLE_FAST 1 -#endif - -/* - * ARM, little-endian. - */ -#elif defined __arm__ && __ARMEL__ - -#define SPH_DETECT_LITTLE_ENDIAN 1 - -/* - * MIPS, little-endian. - */ -#elif MIPSEL || _MIPSEL || __MIPSEL || __MIPSEL__ - -#define SPH_DETECT_LITTLE_ENDIAN 1 - -/* - * MIPS, big-endian. - */ -#elif MIPSEB || _MIPSEB || __MIPSEB || __MIPSEB__ - -#define SPH_DETECT_BIG_ENDIAN 1 - -/* - * PowerPC. - */ -#elif defined __powerpc__ || defined __POWERPC__ || defined __ppc__ \ - || defined _ARCH_PPC - -/* - * Note: we do not declare cross-endian access to be "fast": even if - * using inline assembly, implementation should still assume that - * keeping the decoded word in a temporary is faster than decoding - * it again. - */ -#if defined __GNUC__ -#if SPH_64_TRUE -#define SPH_DETECT_PPC64_GCC 1 -#else -#define SPH_DETECT_PPC32_GCC 1 -#endif -#endif - -#if defined __BIG_ENDIAN__ || defined _BIG_ENDIAN -#define SPH_DETECT_BIG_ENDIAN 1 -#elif defined __LITTLE_ENDIAN__ || defined _LITTLE_ENDIAN -#define SPH_DETECT_LITTLE_ENDIAN 1 -#endif - -/* - * Itanium, 64-bit. - */ -#elif defined __ia64 || defined __ia64__ \ - || defined __itanium__ || defined _M_IA64 - -#if defined __BIG_ENDIAN__ || defined _BIG_ENDIAN -#define SPH_DETECT_BIG_ENDIAN 1 -#else -#define SPH_DETECT_LITTLE_ENDIAN 1 -#endif -#if defined __LP64__ || defined _LP64 -#define SPH_DETECT_UPTR sph_u64 -#else -#define SPH_DETECT_UPTR sph_u32 -#endif - -#endif - -#if defined SPH_DETECT_SPARCV9_GCC_32 || defined SPH_DETECT_SPARCV9_GCC_64 -#define SPH_DETECT_SPARCV9_GCC 1 -#endif - -#if defined SPH_DETECT_UNALIGNED && !defined SPH_UNALIGNED -#define SPH_UNALIGNED SPH_DETECT_UNALIGNED -#endif -#if defined SPH_DETECT_UPTR && !defined SPH_UPTR -#define SPH_UPTR SPH_DETECT_UPTR -#endif -#if defined SPH_DETECT_LITTLE_ENDIAN && !defined SPH_LITTLE_ENDIAN -#define SPH_LITTLE_ENDIAN SPH_DETECT_LITTLE_ENDIAN -#endif -#if defined SPH_DETECT_BIG_ENDIAN && !defined SPH_BIG_ENDIAN -#define SPH_BIG_ENDIAN SPH_DETECT_BIG_ENDIAN -#endif -#if defined SPH_DETECT_LITTLE_FAST && !defined SPH_LITTLE_FAST -#define SPH_LITTLE_FAST SPH_DETECT_LITTLE_FAST -#endif -#if defined SPH_DETECT_BIG_FAST && !defined SPH_BIG_FAST -#define SPH_BIG_FAST SPH_DETECT_BIG_FAST -#endif -#if defined SPH_DETECT_SPARCV9_GCC_32 && !defined SPH_SPARCV9_GCC_32 -#define SPH_SPARCV9_GCC_32 SPH_DETECT_SPARCV9_GCC_32 -#endif -#if defined SPH_DETECT_SPARCV9_GCC_64 && !defined SPH_SPARCV9_GCC_64 -#define SPH_SPARCV9_GCC_64 SPH_DETECT_SPARCV9_GCC_64 -#endif -#if defined SPH_DETECT_SPARCV9_GCC && !defined SPH_SPARCV9_GCC -#define SPH_SPARCV9_GCC SPH_DETECT_SPARCV9_GCC -#endif -#if defined SPH_DETECT_I386_GCC && !defined SPH_I386_GCC -#define SPH_I386_GCC SPH_DETECT_I386_GCC -#endif -#if defined SPH_DETECT_I386_MSVC && !defined SPH_I386_MSVC -#define SPH_I386_MSVC SPH_DETECT_I386_MSVC -#endif -#if defined SPH_DETECT_AMD64_GCC && !defined SPH_AMD64_GCC -#define SPH_AMD64_GCC SPH_DETECT_AMD64_GCC -#endif -#if defined SPH_DETECT_AMD64_MSVC && !defined SPH_AMD64_MSVC -#define SPH_AMD64_MSVC SPH_DETECT_AMD64_MSVC -#endif -#if defined SPH_DETECT_PPC32_GCC && !defined SPH_PPC32_GCC -#define SPH_PPC32_GCC SPH_DETECT_PPC32_GCC -#endif -#if defined SPH_DETECT_PPC64_GCC && !defined SPH_PPC64_GCC -#define SPH_PPC64_GCC SPH_DETECT_PPC64_GCC -#endif - -#if SPH_LITTLE_ENDIAN && !defined SPH_LITTLE_FAST -#define SPH_LITTLE_FAST 1 -#endif -#if SPH_BIG_ENDIAN && !defined SPH_BIG_FAST -#define SPH_BIG_FAST 1 -#endif - -#if defined SPH_UPTR && !(SPH_LITTLE_ENDIAN || SPH_BIG_ENDIAN) -#error SPH_UPTR defined, but endianness is not known. -#endif - -#if SPH_I386_GCC && !SPH_NO_ASM - -/* - * On x86 32-bit, with gcc, we use the bswapl opcode to byte-swap 32-bit - * values. - */ - -static SPH_INLINE sph_u32 -sph_bswap32(sph_u32 x) -{ - __asm__ __volatile__ ("bswapl %0" : "=r" (x) : "0" (x)); - return x; -} - -#if SPH_64 - -static SPH_INLINE sph_u64 -sph_bswap64(sph_u64 x) -{ - return ((sph_u64)sph_bswap32((sph_u32)x) << 32) - | (sph_u64)sph_bswap32((sph_u32)(x >> 32)); -} - -#endif - -#elif SPH_AMD64_GCC && !SPH_NO_ASM - -/* - * On x86 64-bit, with gcc, we use the bswapl opcode to byte-swap 32-bit - * and 64-bit values. - */ - -static SPH_INLINE sph_u32 -sph_bswap32(sph_u32 x) -{ - __asm__ __volatile__ ("bswapl %0" : "=r" (x) : "0" (x)); - return x; -} - -#if SPH_64 - -static SPH_INLINE sph_u64 -sph_bswap64(sph_u64 x) -{ - __asm__ __volatile__ ("bswapq %0" : "=r" (x) : "0" (x)); - return x; -} - -#endif - -/* - * Disabled code. Apparently, Microsoft Visual C 2005 is smart enough - * to generate proper opcodes for endianness swapping with the pure C - * implementation below. - * - -#elif SPH_I386_MSVC && !SPH_NO_ASM - -static __inline sph_u32 __declspec(naked) __fastcall -sph_bswap32(sph_u32 x) -{ - __asm { - bswap ecx - mov eax,ecx - ret - } -} - -#if SPH_64 - -static SPH_INLINE sph_u64 -sph_bswap64(sph_u64 x) -{ - return ((sph_u64)sph_bswap32((sph_u32)x) << 32) - | (sph_u64)sph_bswap32((sph_u32)(x >> 32)); -} - -#endif - - * - * [end of disabled code] - */ - -#else - -static SPH_INLINE sph_u32 -sph_bswap32(sph_u32 x) -{ - x = SPH_T32((x << 16) | (x >> 16)); - x = ((x & SPH_C32(0xFF00FF00)) >> 8) - | ((x & SPH_C32(0x00FF00FF)) << 8); - return x; -} - -#if SPH_64 - -/** - * Byte-swap a 64-bit value. - * - * @param x the input value - * @return the byte-swapped value - */ -static SPH_INLINE sph_u64 -sph_bswap64(sph_u64 x) -{ - x = SPH_T64((x << 32) | (x >> 32)); - x = ((x & SPH_C64(0xFFFF0000FFFF0000)) >> 16) - | ((x & SPH_C64(0x0000FFFF0000FFFF)) << 16); - x = ((x & SPH_C64(0xFF00FF00FF00FF00)) >> 8) - | ((x & SPH_C64(0x00FF00FF00FF00FF)) << 8); - return x; -} - -#endif - -#endif - -#if SPH_SPARCV9_GCC && !SPH_NO_ASM - -/* - * On UltraSPARC systems, native ordering is big-endian, but it is - * possible to perform little-endian read accesses by specifying the - * address space 0x88 (ASI_PRIMARY_LITTLE). Basically, either we use - * the opcode "lda [%reg]0x88,%dst", where %reg is the register which - * contains the source address and %dst is the destination register, - * or we use "lda [%reg+imm]%asi,%dst", which uses the %asi register - * to get the address space name. The latter format is better since it - * combines an addition and the actual access in a single opcode; but - * it requires the setting (and subsequent resetting) of %asi, which is - * slow. Some operations (i.e. MD5 compression function) combine many - * successive little-endian read accesses, which may share the same - * %asi setting. The macros below contain the appropriate inline - * assembly. - */ - -#define SPH_SPARCV9_SET_ASI \ - sph_u32 sph_sparcv9_asi; \ - __asm__ __volatile__ ( \ - "rd %%asi,%0\n\twr %%g0,0x88,%%asi" : "=r" (sph_sparcv9_asi)); - -#define SPH_SPARCV9_RESET_ASI \ - __asm__ __volatile__ ("wr %%g0,%0,%%asi" : : "r" (sph_sparcv9_asi)); - -#define SPH_SPARCV9_DEC32LE(base, idx) ({ \ - sph_u32 sph_sparcv9_tmp; \ - __asm__ __volatile__ ("lda [%1+" #idx "*4]%%asi,%0" \ - : "=r" (sph_sparcv9_tmp) : "r" (base)); \ - sph_sparcv9_tmp; \ - }) - -#endif - -static SPH_INLINE void -sph_enc16be(void *dst, unsigned val) -{ - ((unsigned char *)dst)[0] = (val >> 8); - ((unsigned char *)dst)[1] = val; -} - -static SPH_INLINE unsigned -sph_dec16be(const void *src) -{ - return ((unsigned)(((const unsigned char *)src)[0]) << 8) - | (unsigned)(((const unsigned char *)src)[1]); -} - -static SPH_INLINE void -sph_enc16le(void *dst, unsigned val) -{ - ((unsigned char *)dst)[0] = val; - ((unsigned char *)dst)[1] = val >> 8; -} - -static SPH_INLINE unsigned -sph_dec16le(const void *src) -{ - return (unsigned)(((const unsigned char *)src)[0]) - | ((unsigned)(((const unsigned char *)src)[1]) << 8); -} - -/** - * Encode a 32-bit value into the provided buffer (big endian convention). - * - * @param dst the destination buffer - * @param val the 32-bit value to encode - */ -static SPH_INLINE void -sph_enc32be(void *dst, sph_u32 val) -{ -#if defined SPH_UPTR -#if SPH_UNALIGNED -#if SPH_LITTLE_ENDIAN - val = sph_bswap32(val); -#endif - *(sph_u32 *)dst = val; -#else - if (((SPH_UPTR)dst & 3) == 0) { -#if SPH_LITTLE_ENDIAN - val = sph_bswap32(val); -#endif - *(sph_u32 *)dst = val; - } else { - ((unsigned char *)dst)[0] = (val >> 24); - ((unsigned char *)dst)[1] = (val >> 16); - ((unsigned char *)dst)[2] = (val >> 8); - ((unsigned char *)dst)[3] = val; - } -#endif -#else - ((unsigned char *)dst)[0] = (val >> 24); - ((unsigned char *)dst)[1] = (val >> 16); - ((unsigned char *)dst)[2] = (val >> 8); - ((unsigned char *)dst)[3] = val; -#endif -} - -/** - * Encode a 32-bit value into the provided buffer (big endian convention). - * The destination buffer must be properly aligned. - * - * @param dst the destination buffer (32-bit aligned) - * @param val the value to encode - */ -static SPH_INLINE void -sph_enc32be_aligned(void *dst, sph_u32 val) -{ -#if SPH_LITTLE_ENDIAN - *(sph_u32 *)dst = sph_bswap32(val); -#elif SPH_BIG_ENDIAN - *(sph_u32 *)dst = val; -#else - ((unsigned char *)dst)[0] = (val >> 24); - ((unsigned char *)dst)[1] = (val >> 16); - ((unsigned char *)dst)[2] = (val >> 8); - ((unsigned char *)dst)[3] = val; -#endif -} - -/** - * Decode a 32-bit value from the provided buffer (big endian convention). - * - * @param src the source buffer - * @return the decoded value - */ -static SPH_INLINE sph_u32 -sph_dec32be(const void *src) -{ -#if defined SPH_UPTR -#if SPH_UNALIGNED -#if SPH_LITTLE_ENDIAN - return sph_bswap32(*(const sph_u32 *)src); -#else - return *(const sph_u32 *)src; -#endif -#else - if (((SPH_UPTR)src & 3) == 0) { -#if SPH_LITTLE_ENDIAN - return sph_bswap32(*(const sph_u32 *)src); -#else - return *(const sph_u32 *)src; -#endif - } else { - return ((sph_u32)(((const unsigned char *)src)[0]) << 24) - | ((sph_u32)(((const unsigned char *)src)[1]) << 16) - | ((sph_u32)(((const unsigned char *)src)[2]) << 8) - | (sph_u32)(((const unsigned char *)src)[3]); - } -#endif -#else - return ((sph_u32)(((const unsigned char *)src)[0]) << 24) - | ((sph_u32)(((const unsigned char *)src)[1]) << 16) - | ((sph_u32)(((const unsigned char *)src)[2]) << 8) - | (sph_u32)(((const unsigned char *)src)[3]); -#endif -} - -/** - * Decode a 32-bit value from the provided buffer (big endian convention). - * The source buffer must be properly aligned. - * - * @param src the source buffer (32-bit aligned) - * @return the decoded value - */ -static SPH_INLINE sph_u32 -sph_dec32be_aligned(const void *src) -{ -#if SPH_LITTLE_ENDIAN - return sph_bswap32(*(const sph_u32 *)src); -#elif SPH_BIG_ENDIAN - return *(const sph_u32 *)src; -#else - return ((sph_u32)(((const unsigned char *)src)[0]) << 24) - | ((sph_u32)(((const unsigned char *)src)[1]) << 16) - | ((sph_u32)(((const unsigned char *)src)[2]) << 8) - | (sph_u32)(((const unsigned char *)src)[3]); -#endif -} - -/** - * Encode a 32-bit value into the provided buffer (little endian convention). - * - * @param dst the destination buffer - * @param val the 32-bit value to encode - */ -static SPH_INLINE void -sph_enc32le(void *dst, sph_u32 val) -{ -#if defined SPH_UPTR -#if SPH_UNALIGNED -#if SPH_BIG_ENDIAN - val = sph_bswap32(val); -#endif - *(sph_u32 *)dst = val; -#else - if (((SPH_UPTR)dst & 3) == 0) { -#if SPH_BIG_ENDIAN - val = sph_bswap32(val); -#endif - *(sph_u32 *)dst = val; - } else { - ((unsigned char *)dst)[0] = val; - ((unsigned char *)dst)[1] = (val >> 8); - ((unsigned char *)dst)[2] = (val >> 16); - ((unsigned char *)dst)[3] = (val >> 24); - } -#endif -#else - ((unsigned char *)dst)[0] = val; - ((unsigned char *)dst)[1] = (val >> 8); - ((unsigned char *)dst)[2] = (val >> 16); - ((unsigned char *)dst)[3] = (val >> 24); -#endif -} - -/** - * Encode a 32-bit value into the provided buffer (little endian convention). - * The destination buffer must be properly aligned. - * - * @param dst the destination buffer (32-bit aligned) - * @param val the value to encode - */ -static SPH_INLINE void -sph_enc32le_aligned(void *dst, sph_u32 val) -{ -#if SPH_LITTLE_ENDIAN - *(sph_u32 *)dst = val; -#elif SPH_BIG_ENDIAN - *(sph_u32 *)dst = sph_bswap32(val); -#else - ((unsigned char *)dst)[0] = val; - ((unsigned char *)dst)[1] = (val >> 8); - ((unsigned char *)dst)[2] = (val >> 16); - ((unsigned char *)dst)[3] = (val >> 24); -#endif -} - -/** - * Decode a 32-bit value from the provided buffer (little endian convention). - * - * @param src the source buffer - * @return the decoded value - */ -static SPH_INLINE sph_u32 -sph_dec32le(const void *src) -{ -#if defined SPH_UPTR -#if SPH_UNALIGNED -#if SPH_BIG_ENDIAN - return sph_bswap32(*(const sph_u32 *)src); -#else - return *(const sph_u32 *)src; -#endif -#else - if (((SPH_UPTR)src & 3) == 0) { -#if SPH_BIG_ENDIAN -#if SPH_SPARCV9_GCC && !SPH_NO_ASM - sph_u32 tmp; - - /* - * "__volatile__" is needed here because without it, - * gcc-3.4.3 miscompiles the code and performs the - * access before the test on the address, thus triggering - * a bus error... - */ - __asm__ __volatile__ ( - "lda [%1]0x88,%0" : "=r" (tmp) : "r" (src)); - return tmp; -/* - * On PowerPC, this turns out not to be worth the effort: the inline - * assembly makes GCC optimizer uncomfortable, which tends to nullify - * the decoding gains. - * - * For most hash functions, using this inline assembly trick changes - * hashing speed by less than 5% and often _reduces_ it. The biggest - * gains are for MD4 (+11%) and CubeHash (+30%). For all others, it is - * less then 10%. The speed gain on CubeHash is probably due to the - * chronic shortage of registers that CubeHash endures; for the other - * functions, the generic code appears to be efficient enough already. - * -#elif (SPH_PPC32_GCC || SPH_PPC64_GCC) && !SPH_NO_ASM - sph_u32 tmp; - - __asm__ __volatile__ ( - "lwbrx %0,0,%1" : "=r" (tmp) : "r" (src)); - return tmp; - */ -#else - return sph_bswap32(*(const sph_u32 *)src); -#endif -#else - return *(const sph_u32 *)src; -#endif - } else { - return (sph_u32)(((const unsigned char *)src)[0]) - | ((sph_u32)(((const unsigned char *)src)[1]) << 8) - | ((sph_u32)(((const unsigned char *)src)[2]) << 16) - | ((sph_u32)(((const unsigned char *)src)[3]) << 24); - } -#endif -#else - return (sph_u32)(((const unsigned char *)src)[0]) - | ((sph_u32)(((const unsigned char *)src)[1]) << 8) - | ((sph_u32)(((const unsigned char *)src)[2]) << 16) - | ((sph_u32)(((const unsigned char *)src)[3]) << 24); -#endif -} - -/** - * Decode a 32-bit value from the provided buffer (little endian convention). - * The source buffer must be properly aligned. - * - * @param src the source buffer (32-bit aligned) - * @return the decoded value - */ -static SPH_INLINE sph_u32 -sph_dec32le_aligned(const void *src) -{ -#if SPH_LITTLE_ENDIAN - return *(const sph_u32 *)src; -#elif SPH_BIG_ENDIAN -#if SPH_SPARCV9_GCC && !SPH_NO_ASM - sph_u32 tmp; - - __asm__ __volatile__ ("lda [%1]0x88,%0" : "=r" (tmp) : "r" (src)); - return tmp; -/* - * Not worth it generally. - * -#elif (SPH_PPC32_GCC || SPH_PPC64_GCC) && !SPH_NO_ASM - sph_u32 tmp; - - __asm__ __volatile__ ("lwbrx %0,0,%1" : "=r" (tmp) : "r" (src)); - return tmp; - */ -#else - return sph_bswap32(*(const sph_u32 *)src); -#endif -#else - return (sph_u32)(((const unsigned char *)src)[0]) - | ((sph_u32)(((const unsigned char *)src)[1]) << 8) - | ((sph_u32)(((const unsigned char *)src)[2]) << 16) - | ((sph_u32)(((const unsigned char *)src)[3]) << 24); -#endif -} - -#if SPH_64 - -/** - * Encode a 64-bit value into the provided buffer (big endian convention). - * - * @param dst the destination buffer - * @param val the 64-bit value to encode - */ -static SPH_INLINE void -sph_enc64be(void *dst, sph_u64 val) -{ -#if defined SPH_UPTR -#if SPH_UNALIGNED -#if SPH_LITTLE_ENDIAN - val = sph_bswap64(val); -#endif - *(sph_u64 *)dst = val; -#else - if (((SPH_UPTR)dst & 7) == 0) { -#if SPH_LITTLE_ENDIAN - val = sph_bswap64(val); -#endif - *(sph_u64 *)dst = val; - } else { - ((unsigned char *)dst)[0] = (val >> 56); - ((unsigned char *)dst)[1] = (val >> 48); - ((unsigned char *)dst)[2] = (val >> 40); - ((unsigned char *)dst)[3] = (val >> 32); - ((unsigned char *)dst)[4] = (val >> 24); - ((unsigned char *)dst)[5] = (val >> 16); - ((unsigned char *)dst)[6] = (val >> 8); - ((unsigned char *)dst)[7] = val; - } -#endif -#else - ((unsigned char *)dst)[0] = (val >> 56); - ((unsigned char *)dst)[1] = (val >> 48); - ((unsigned char *)dst)[2] = (val >> 40); - ((unsigned char *)dst)[3] = (val >> 32); - ((unsigned char *)dst)[4] = (val >> 24); - ((unsigned char *)dst)[5] = (val >> 16); - ((unsigned char *)dst)[6] = (val >> 8); - ((unsigned char *)dst)[7] = val; -#endif -} - -/** - * Encode a 64-bit value into the provided buffer (big endian convention). - * The destination buffer must be properly aligned. - * - * @param dst the destination buffer (64-bit aligned) - * @param val the value to encode - */ -static SPH_INLINE void -sph_enc64be_aligned(void *dst, sph_u64 val) -{ -#if SPH_LITTLE_ENDIAN - *(sph_u64 *)dst = sph_bswap64(val); -#elif SPH_BIG_ENDIAN - *(sph_u64 *)dst = val; -#else - ((unsigned char *)dst)[0] = (val >> 56); - ((unsigned char *)dst)[1] = (val >> 48); - ((unsigned char *)dst)[2] = (val >> 40); - ((unsigned char *)dst)[3] = (val >> 32); - ((unsigned char *)dst)[4] = (val >> 24); - ((unsigned char *)dst)[5] = (val >> 16); - ((unsigned char *)dst)[6] = (val >> 8); - ((unsigned char *)dst)[7] = val; -#endif -} - -/** - * Decode a 64-bit value from the provided buffer (big endian convention). - * - * @param src the source buffer - * @return the decoded value - */ -static SPH_INLINE sph_u64 -sph_dec64be(const void *src) -{ -#if defined SPH_UPTR -#if SPH_UNALIGNED -#if SPH_LITTLE_ENDIAN - return sph_bswap64(*(const sph_u64 *)src); -#else - return *(const sph_u64 *)src; -#endif -#else - if (((SPH_UPTR)src & 7) == 0) { -#if SPH_LITTLE_ENDIAN - return sph_bswap64(*(const sph_u64 *)src); -#else - return *(const sph_u64 *)src; -#endif - } else { - return ((sph_u64)(((const unsigned char *)src)[0]) << 56) - | ((sph_u64)(((const unsigned char *)src)[1]) << 48) - | ((sph_u64)(((const unsigned char *)src)[2]) << 40) - | ((sph_u64)(((const unsigned char *)src)[3]) << 32) - | ((sph_u64)(((const unsigned char *)src)[4]) << 24) - | ((sph_u64)(((const unsigned char *)src)[5]) << 16) - | ((sph_u64)(((const unsigned char *)src)[6]) << 8) - | (sph_u64)(((const unsigned char *)src)[7]); - } -#endif -#else - return ((sph_u64)(((const unsigned char *)src)[0]) << 56) - | ((sph_u64)(((const unsigned char *)src)[1]) << 48) - | ((sph_u64)(((const unsigned char *)src)[2]) << 40) - | ((sph_u64)(((const unsigned char *)src)[3]) << 32) - | ((sph_u64)(((const unsigned char *)src)[4]) << 24) - | ((sph_u64)(((const unsigned char *)src)[5]) << 16) - | ((sph_u64)(((const unsigned char *)src)[6]) << 8) - | (sph_u64)(((const unsigned char *)src)[7]); -#endif -} - -/** - * Decode a 64-bit value from the provided buffer (big endian convention). - * The source buffer must be properly aligned. - * - * @param src the source buffer (64-bit aligned) - * @return the decoded value - */ -static SPH_INLINE sph_u64 -sph_dec64be_aligned(const void *src) -{ -#if SPH_LITTLE_ENDIAN - return sph_bswap64(*(const sph_u64 *)src); -#elif SPH_BIG_ENDIAN - return *(const sph_u64 *)src; -#else - return ((sph_u64)(((const unsigned char *)src)[0]) << 56) - | ((sph_u64)(((const unsigned char *)src)[1]) << 48) - | ((sph_u64)(((const unsigned char *)src)[2]) << 40) - | ((sph_u64)(((const unsigned char *)src)[3]) << 32) - | ((sph_u64)(((const unsigned char *)src)[4]) << 24) - | ((sph_u64)(((const unsigned char *)src)[5]) << 16) - | ((sph_u64)(((const unsigned char *)src)[6]) << 8) - | (sph_u64)(((const unsigned char *)src)[7]); -#endif -} - -/** - * Encode a 64-bit value into the provided buffer (little endian convention). - * - * @param dst the destination buffer - * @param val the 64-bit value to encode - */ -static SPH_INLINE void -sph_enc64le(void *dst, sph_u64 val) -{ -#if defined SPH_UPTR -#if SPH_UNALIGNED -#if SPH_BIG_ENDIAN - val = sph_bswap64(val); -#endif - *(sph_u64 *)dst = val; -#else - if (((SPH_UPTR)dst & 7) == 0) { -#if SPH_BIG_ENDIAN - val = sph_bswap64(val); -#endif - *(sph_u64 *)dst = val; - } else { - ((unsigned char *)dst)[0] = val; - ((unsigned char *)dst)[1] = (val >> 8); - ((unsigned char *)dst)[2] = (val >> 16); - ((unsigned char *)dst)[3] = (val >> 24); - ((unsigned char *)dst)[4] = (val >> 32); - ((unsigned char *)dst)[5] = (val >> 40); - ((unsigned char *)dst)[6] = (val >> 48); - ((unsigned char *)dst)[7] = (val >> 56); - } -#endif -#else - ((unsigned char *)dst)[0] = val; - ((unsigned char *)dst)[1] = (val >> 8); - ((unsigned char *)dst)[2] = (val >> 16); - ((unsigned char *)dst)[3] = (val >> 24); - ((unsigned char *)dst)[4] = (val >> 32); - ((unsigned char *)dst)[5] = (val >> 40); - ((unsigned char *)dst)[6] = (val >> 48); - ((unsigned char *)dst)[7] = (val >> 56); -#endif -} - -/** - * Encode a 64-bit value into the provided buffer (little endian convention). - * The destination buffer must be properly aligned. - * - * @param dst the destination buffer (64-bit aligned) - * @param val the value to encode - */ -static SPH_INLINE void -sph_enc64le_aligned(void *dst, sph_u64 val) -{ -#if SPH_LITTLE_ENDIAN - *(sph_u64 *)dst = val; -#elif SPH_BIG_ENDIAN - *(sph_u64 *)dst = sph_bswap64(val); -#else - ((unsigned char *)dst)[0] = val; - ((unsigned char *)dst)[1] = (val >> 8); - ((unsigned char *)dst)[2] = (val >> 16); - ((unsigned char *)dst)[3] = (val >> 24); - ((unsigned char *)dst)[4] = (val >> 32); - ((unsigned char *)dst)[5] = (val >> 40); - ((unsigned char *)dst)[6] = (val >> 48); - ((unsigned char *)dst)[7] = (val >> 56); -#endif -} - -/** - * Decode a 64-bit value from the provided buffer (little endian convention). - * - * @param src the source buffer - * @return the decoded value - */ -static SPH_INLINE sph_u64 -sph_dec64le(const void *src) -{ -#if defined SPH_UPTR -#if SPH_UNALIGNED -#if SPH_BIG_ENDIAN - return sph_bswap64(*(const sph_u64 *)src); -#else - return *(const sph_u64 *)src; -#endif -#else - if (((SPH_UPTR)src & 7) == 0) { -#if SPH_BIG_ENDIAN -#if SPH_SPARCV9_GCC_64 && !SPH_NO_ASM - sph_u64 tmp; - - __asm__ __volatile__ ( - "ldxa [%1]0x88,%0" : "=r" (tmp) : "r" (src)); - return tmp; -/* - * Not worth it generally. - * -#elif SPH_PPC32_GCC && !SPH_NO_ASM - return (sph_u64)sph_dec32le_aligned(src) - | ((sph_u64)sph_dec32le_aligned( - (const char *)src + 4) << 32); -#elif SPH_PPC64_GCC && !SPH_NO_ASM - sph_u64 tmp; - - __asm__ __volatile__ ( - "ldbrx %0,0,%1" : "=r" (tmp) : "r" (src)); - return tmp; - */ -#else - return sph_bswap64(*(const sph_u64 *)src); -#endif -#else - return *(const sph_u64 *)src; -#endif - } else { - return (sph_u64)(((const unsigned char *)src)[0]) - | ((sph_u64)(((const unsigned char *)src)[1]) << 8) - | ((sph_u64)(((const unsigned char *)src)[2]) << 16) - | ((sph_u64)(((const unsigned char *)src)[3]) << 24) - | ((sph_u64)(((const unsigned char *)src)[4]) << 32) - | ((sph_u64)(((const unsigned char *)src)[5]) << 40) - | ((sph_u64)(((const unsigned char *)src)[6]) << 48) - | ((sph_u64)(((const unsigned char *)src)[7]) << 56); - } -#endif -#else - return (sph_u64)(((const unsigned char *)src)[0]) - | ((sph_u64)(((const unsigned char *)src)[1]) << 8) - | ((sph_u64)(((const unsigned char *)src)[2]) << 16) - | ((sph_u64)(((const unsigned char *)src)[3]) << 24) - | ((sph_u64)(((const unsigned char *)src)[4]) << 32) - | ((sph_u64)(((const unsigned char *)src)[5]) << 40) - | ((sph_u64)(((const unsigned char *)src)[6]) << 48) - | ((sph_u64)(((const unsigned char *)src)[7]) << 56); -#endif -} - -/** - * Decode a 64-bit value from the provided buffer (little endian convention). - * The source buffer must be properly aligned. - * - * @param src the source buffer (64-bit aligned) - * @return the decoded value - */ -static SPH_INLINE sph_u64 -sph_dec64le_aligned(const void *src) -{ -#if SPH_LITTLE_ENDIAN - return *(const sph_u64 *)src; -#elif SPH_BIG_ENDIAN -#if SPH_SPARCV9_GCC_64 && !SPH_NO_ASM - sph_u64 tmp; - - __asm__ __volatile__ ("ldxa [%1]0x88,%0" : "=r" (tmp) : "r" (src)); - return tmp; -/* - * Not worth it generally. - * -#elif SPH_PPC32_GCC && !SPH_NO_ASM - return (sph_u64)sph_dec32le_aligned(src) - | ((sph_u64)sph_dec32le_aligned((const char *)src + 4) << 32); -#elif SPH_PPC64_GCC && !SPH_NO_ASM - sph_u64 tmp; - - __asm__ __volatile__ ("ldbrx %0,0,%1" : "=r" (tmp) : "r" (src)); - return tmp; - */ -#else - return sph_bswap64(*(const sph_u64 *)src); -#endif -#else - return (sph_u64)(((const unsigned char *)src)[0]) - | ((sph_u64)(((const unsigned char *)src)[1]) << 8) - | ((sph_u64)(((const unsigned char *)src)[2]) << 16) - | ((sph_u64)(((const unsigned char *)src)[3]) << 24) - | ((sph_u64)(((const unsigned char *)src)[4]) << 32) - | ((sph_u64)(((const unsigned char *)src)[5]) << 40) - | ((sph_u64)(((const unsigned char *)src)[6]) << 48) - | ((sph_u64)(((const unsigned char *)src)[7]) << 56); -#endif -} - -#endif - -#endif /* Doxygen excluded block */ - -#endif diff --git a/src/hash.h b/src/hash.h index 9c5831da9735..d8a15b8a1128 100644 --- a/src/hash.h +++ b/src/hash.h @@ -15,17 +15,17 @@ #include "uint256.h" #include "version.h" -#include "crypto/sph_blake.h" -#include "crypto/sph_bmw.h" -#include "crypto/sph_groestl.h" -#include "crypto/sph_jh.h" -#include "crypto/sph_keccak.h" -#include "crypto/sph_skein.h" -#include "crypto/sph_luffa.h" -#include "crypto/sph_cubehash.h" -#include "crypto/sph_shavite.h" -#include "crypto/sph_simd.h" -#include "crypto/sph_echo.h" +#include "crypto/Lyra2RE/sph_blake.h" +#include "crypto/Lyra2RE/sph_bmw.h" +#include "crypto/Lyra2RE/sph_groestl.h" +#include "crypto/Lyra2RE/sph_jh.h" +#include "crypto/Lyra2RE/sph_keccak.h" +#include "crypto/Lyra2RE/sph_skein.h" +#include "crypto/Lyra2RE/sph_luffa.h" +#include "crypto/Lyra2RE/sph_cubehash.h" +#include "crypto/Lyra2RE/sph_shavite.h" +#include "crypto/Lyra2RE/sph_simd.h" +#include "crypto/Lyra2RE/sph_echo.h" #include @@ -312,71 +312,4 @@ class CSipHasher uint64_t SipHashUint256(uint64_t k0, uint64_t k1, const uint256& val); uint64_t SipHashUint256Extra(uint64_t k0, uint64_t k1, const uint256& val, uint32_t extra); -/* ----------- Absolute Hash ------------------------------------------------ */ -template -inline uint256 HashX11(const T1 pbegin, const T1 pend) - -{ - sph_blake512_context ctx_blake; - sph_bmw512_context ctx_bmw; - sph_groestl512_context ctx_groestl; - sph_jh512_context ctx_jh; - sph_keccak512_context ctx_keccak; - sph_skein512_context ctx_skein; - sph_luffa512_context ctx_luffa; - sph_cubehash512_context ctx_cubehash; - sph_shavite512_context ctx_shavite; - sph_simd512_context ctx_simd; - sph_echo512_context ctx_echo; - static unsigned char pblank[1]; - - uint512 hash[11]; - - sph_blake512_init(&ctx_blake); - sph_blake512 (&ctx_blake, (pbegin == pend ? pblank : static_cast(&pbegin[0])), (pend - pbegin) * sizeof(pbegin[0])); - sph_blake512_close(&ctx_blake, static_cast(&hash[0])); - - sph_bmw512_init(&ctx_bmw); - sph_bmw512 (&ctx_bmw, static_cast(&hash[0]), 64); - sph_bmw512_close(&ctx_bmw, static_cast(&hash[1])); - - sph_groestl512_init(&ctx_groestl); - sph_groestl512 (&ctx_groestl, static_cast(&hash[1]), 64); - sph_groestl512_close(&ctx_groestl, static_cast(&hash[2])); - - sph_skein512_init(&ctx_skein); - sph_skein512 (&ctx_skein, static_cast(&hash[2]), 64); - sph_skein512_close(&ctx_skein, static_cast(&hash[3])); - - sph_jh512_init(&ctx_jh); - sph_jh512 (&ctx_jh, static_cast(&hash[3]), 64); - sph_jh512_close(&ctx_jh, static_cast(&hash[4])); - - sph_keccak512_init(&ctx_keccak); - sph_keccak512 (&ctx_keccak, static_cast(&hash[4]), 64); - sph_keccak512_close(&ctx_keccak, static_cast(&hash[5])); - - sph_luffa512_init(&ctx_luffa); - sph_luffa512 (&ctx_luffa, static_cast(&hash[5]), 64); - sph_luffa512_close(&ctx_luffa, static_cast(&hash[6])); - - sph_cubehash512_init(&ctx_cubehash); - sph_cubehash512 (&ctx_cubehash, static_cast(&hash[6]), 64); - sph_cubehash512_close(&ctx_cubehash, static_cast(&hash[7])); - - sph_shavite512_init(&ctx_shavite); - sph_shavite512(&ctx_shavite, static_cast(&hash[7]), 64); - sph_shavite512_close(&ctx_shavite, static_cast(&hash[8])); - - sph_simd512_init(&ctx_simd); - sph_simd512 (&ctx_simd, static_cast(&hash[8]), 64); - sph_simd512_close(&ctx_simd, static_cast(&hash[9])); - - sph_echo512_init(&ctx_echo); - sph_echo512 (&ctx_echo, static_cast(&hash[9]), 64); - sph_echo512_close(&ctx_echo, static_cast(&hash[10])); - - return hash[10].trim256(); -} - #endif // BITCOIN_HASH_H From b3c91ef5474c9356e405b206ee5d36105cc8186d Mon Sep 17 00:00:00 2001 From: CryptoCentric Date: Wed, 17 Apr 2019 15:19:15 +0100 Subject: [PATCH 003/282] Add missing seperator Move hashing files to Lyra2RE --- src/Makefile.am | 4 +- src/crypto/{ => Lyra2RE}/aes_helper.c | 2 +- src/crypto/{ => Lyra2RE}/jh.c | 0 src/crypto/Lyra2RE/keccak.c | 2 +- src/crypto/{ => Lyra2RE}/luffa.c | 0 src/crypto/keccak.c | 1824 ------------------------- 6 files changed, 4 insertions(+), 1828 deletions(-) rename src/crypto/{ => Lyra2RE}/aes_helper.c (99%) rename src/crypto/{ => Lyra2RE}/jh.c (100%) rename src/crypto/{ => Lyra2RE}/luffa.c (100%) delete mode 100644 src/crypto/keccak.c diff --git a/src/Makefile.am b/src/Makefile.am index 7456285e50d7..5c941b0c3ced 100644 --- a/src/Makefile.am +++ b/src/Makefile.am @@ -305,7 +305,6 @@ crypto_libabsolute_crypto_a_SOURCES = \ crypto/hmac_sha512.cpp \ crypto/hmac_sha512.h \ crypto/ripemd160.cpp \ - crypto/aes_helper.c \ crypto/ripemd160.h \ crypto/sha1.cpp \ crypto/sha1.h \ @@ -313,6 +312,7 @@ crypto_libabsolute_crypto_a_SOURCES = \ crypto/sha256.h \ crypto/sha512.cpp \ crypto/sha512.h \ + crypto/Lyra2RE/aes_helper.c \ crypto/Lyra2RE/Lyra2RE.c \ crypto/Lyra2RE/Lyra2RE.h \ crypto/Lyra2RE/Lyra2.c \ @@ -327,7 +327,7 @@ crypto_libabsolute_crypto_a_SOURCES = \ crypto/Lyra2RE/sph_cubehash.h \ crypto/Lyra2RE/blake.c \ crypto/Lyra2RE/keccak.c \ - crypto/Lyra2RE/skein.c + crypto/Lyra2RE/skein.c \ crypto/Lyra2RE/bmw.c \ crypto/Lyra2RE/cubehash.c \ crypto/Lyra2RE/echo.c \ diff --git a/src/crypto/aes_helper.c b/src/crypto/Lyra2RE/aes_helper.c similarity index 99% rename from src/crypto/aes_helper.c rename to src/crypto/Lyra2RE/aes_helper.c index 75b7cc69d057..f60d7a9d84de 100644 --- a/src/crypto/aes_helper.c +++ b/src/crypto/Lyra2RE/aes_helper.c @@ -43,7 +43,7 @@ * @author Thomas Pornin */ -#include "sph_types.h" +#include "Lyra2RE/sph_types.h" #ifdef __cplusplus extern "C"{ #endif diff --git a/src/crypto/jh.c b/src/crypto/Lyra2RE/jh.c similarity index 100% rename from src/crypto/jh.c rename to src/crypto/Lyra2RE/jh.c diff --git a/src/crypto/Lyra2RE/keccak.c b/src/crypto/Lyra2RE/keccak.c index cfd5916788f9..cff9f87dae68 100644 --- a/src/crypto/Lyra2RE/keccak.c +++ b/src/crypto/Lyra2RE/keccak.c @@ -1821,4 +1821,4 @@ sph_keccak512_addbits_and_close(void *cc, unsigned ub, unsigned n, void *dst) #ifdef __cplusplus } -#endif \ No newline at end of file +#endif diff --git a/src/crypto/luffa.c b/src/crypto/Lyra2RE/luffa.c similarity index 100% rename from src/crypto/luffa.c rename to src/crypto/Lyra2RE/luffa.c diff --git a/src/crypto/keccak.c b/src/crypto/keccak.c deleted file mode 100644 index cff9f87dae68..000000000000 --- a/src/crypto/keccak.c +++ /dev/null @@ -1,1824 +0,0 @@ -/* $Id: keccak.c 259 2011-07-19 22:11:27Z tp $ */ -/* - * Keccak implementation. - * - * ==========================(LICENSE BEGIN)============================ - * - * Copyright (c) 2007-2010 Projet RNRT SAPHIR - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY - * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, - * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE - * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - * ===========================(LICENSE END)============================= - * - * @author Thomas Pornin - */ - -#include -#include - -#include "sph_keccak.h" - -#ifdef __cplusplus -extern "C"{ -#endif - -/* - * Parameters: - * - * SPH_KECCAK_64 use a 64-bit type - * SPH_KECCAK_UNROLL number of loops to unroll (0/undef for full unroll) - * SPH_KECCAK_INTERLEAVE use bit-interleaving (32-bit type only) - * SPH_KECCAK_NOCOPY do not copy the state into local variables - * - * If there is no usable 64-bit type, the code automatically switches - * back to the 32-bit implementation. - * - * Some tests on an Intel Core2 Q6600 (both 64-bit and 32-bit, 32 kB L1 - * code cache), a PowerPC (G3, 32 kB L1 code cache), an ARM920T core - * (16 kB L1 code cache), and a small MIPS-compatible CPU (Broadcom BCM3302, - * 8 kB L1 code cache), seem to show that the following are optimal: - * - * -- x86, 64-bit: use the 64-bit implementation, unroll 8 rounds, - * do not copy the state; unrolling 2, 6 or all rounds also provides - * near-optimal performance. - * -- x86, 32-bit: use the 32-bit implementation, unroll 6 rounds, - * interleave, do not copy the state. Unrolling 1, 2, 4 or 8 rounds - * also provides near-optimal performance. - * -- PowerPC: use the 64-bit implementation, unroll 8 rounds, - * copy the state. Unrolling 4 or 6 rounds is near-optimal. - * -- ARM: use the 64-bit implementation, unroll 2 or 4 rounds, - * copy the state. - * -- MIPS: use the 64-bit implementation, unroll 2 rounds, copy - * the state. Unrolling only 1 round is also near-optimal. - * - * Also, interleaving does not always yield actual improvements when - * using a 32-bit implementation; in particular when the architecture - * does not offer a native rotation opcode (interleaving replaces one - * 64-bit rotation with two 32-bit rotations, which is a gain only if - * there is a native 32-bit rotation opcode and not a native 64-bit - * rotation opcode; also, interleaving implies a small overhead when - * processing input words). - * - * To sum up: - * -- when possible, use the 64-bit code - * -- exception: on 32-bit x86, use 32-bit code - * -- when using 32-bit code, use interleaving - * -- copy the state, except on x86 - * -- unroll 8 rounds on "big" machine, 2 rounds on "small" machines - */ - -#if SPH_SMALL_FOOTPRINT && !defined SPH_SMALL_FOOTPRINT_KECCAK -#define SPH_SMALL_FOOTPRINT_KECCAK 1 -#endif - -/* - * By default, we select the 64-bit implementation if a 64-bit type - * is available, unless a 32-bit x86 is detected. - */ -#if !defined SPH_KECCAK_64 && SPH_64 \ - && !(defined __i386__ || SPH_I386_GCC || SPH_I386_MSVC) -#define SPH_KECCAK_64 1 -#endif - -/* - * If using a 32-bit implementation, we prefer to interleave. - */ -#if !SPH_KECCAK_64 && !defined SPH_KECCAK_INTERLEAVE -#define SPH_KECCAK_INTERLEAVE 1 -#endif - -/* - * Unroll 8 rounds on big systems, 2 rounds on small systems. - */ -#ifndef SPH_KECCAK_UNROLL -#if SPH_SMALL_FOOTPRINT_KECCAK -#define SPH_KECCAK_UNROLL 2 -#else -#define SPH_KECCAK_UNROLL 8 -#endif -#endif - -/* - * We do not want to copy the state to local variables on x86 (32-bit - * and 64-bit alike). - */ -#ifndef SPH_KECCAK_NOCOPY -#if defined __i386__ || defined __x86_64 || SPH_I386_MSVC || SPH_I386_GCC -#define SPH_KECCAK_NOCOPY 1 -#else -#define SPH_KECCAK_NOCOPY 0 -#endif -#endif - -#ifdef _MSC_VER -#pragma warning (disable: 4146) -#endif - -#if SPH_KECCAK_64 - -static const sph_u64 RC[] = { - SPH_C64(0x0000000000000001), SPH_C64(0x0000000000008082), - SPH_C64(0x800000000000808A), SPH_C64(0x8000000080008000), - SPH_C64(0x000000000000808B), SPH_C64(0x0000000080000001), - SPH_C64(0x8000000080008081), SPH_C64(0x8000000000008009), - SPH_C64(0x000000000000008A), SPH_C64(0x0000000000000088), - SPH_C64(0x0000000080008009), SPH_C64(0x000000008000000A), - SPH_C64(0x000000008000808B), SPH_C64(0x800000000000008B), - SPH_C64(0x8000000000008089), SPH_C64(0x8000000000008003), - SPH_C64(0x8000000000008002), SPH_C64(0x8000000000000080), - SPH_C64(0x000000000000800A), SPH_C64(0x800000008000000A), - SPH_C64(0x8000000080008081), SPH_C64(0x8000000000008080), - SPH_C64(0x0000000080000001), SPH_C64(0x8000000080008008) -}; - -#if SPH_KECCAK_NOCOPY - -#define a00 (kc->u.wide[ 0]) -#define a10 (kc->u.wide[ 1]) -#define a20 (kc->u.wide[ 2]) -#define a30 (kc->u.wide[ 3]) -#define a40 (kc->u.wide[ 4]) -#define a01 (kc->u.wide[ 5]) -#define a11 (kc->u.wide[ 6]) -#define a21 (kc->u.wide[ 7]) -#define a31 (kc->u.wide[ 8]) -#define a41 (kc->u.wide[ 9]) -#define a02 (kc->u.wide[10]) -#define a12 (kc->u.wide[11]) -#define a22 (kc->u.wide[12]) -#define a32 (kc->u.wide[13]) -#define a42 (kc->u.wide[14]) -#define a03 (kc->u.wide[15]) -#define a13 (kc->u.wide[16]) -#define a23 (kc->u.wide[17]) -#define a33 (kc->u.wide[18]) -#define a43 (kc->u.wide[19]) -#define a04 (kc->u.wide[20]) -#define a14 (kc->u.wide[21]) -#define a24 (kc->u.wide[22]) -#define a34 (kc->u.wide[23]) -#define a44 (kc->u.wide[24]) - -#define DECL_STATE -#define READ_STATE(sc) -#define WRITE_STATE(sc) - -#define INPUT_BUF(size) do { \ - size_t j; \ - for (j = 0; j < (size); j += 8) { \ - kc->u.wide[j >> 3] ^= sph_dec64le_aligned(buf + j); \ - } \ - } while (0) - -#define INPUT_BUF144 INPUT_BUF(144) -#define INPUT_BUF136 INPUT_BUF(136) -#define INPUT_BUF104 INPUT_BUF(104) -#define INPUT_BUF72 INPUT_BUF(72) - -#else - -#define DECL_STATE \ - sph_u64 a00, a01, a02, a03, a04; \ - sph_u64 a10, a11, a12, a13, a14; \ - sph_u64 a20, a21, a22, a23, a24; \ - sph_u64 a30, a31, a32, a33, a34; \ - sph_u64 a40, a41, a42, a43, a44; - -#define READ_STATE(state) do { \ - a00 = (state)->u.wide[ 0]; \ - a10 = (state)->u.wide[ 1]; \ - a20 = (state)->u.wide[ 2]; \ - a30 = (state)->u.wide[ 3]; \ - a40 = (state)->u.wide[ 4]; \ - a01 = (state)->u.wide[ 5]; \ - a11 = (state)->u.wide[ 6]; \ - a21 = (state)->u.wide[ 7]; \ - a31 = (state)->u.wide[ 8]; \ - a41 = (state)->u.wide[ 9]; \ - a02 = (state)->u.wide[10]; \ - a12 = (state)->u.wide[11]; \ - a22 = (state)->u.wide[12]; \ - a32 = (state)->u.wide[13]; \ - a42 = (state)->u.wide[14]; \ - a03 = (state)->u.wide[15]; \ - a13 = (state)->u.wide[16]; \ - a23 = (state)->u.wide[17]; \ - a33 = (state)->u.wide[18]; \ - a43 = (state)->u.wide[19]; \ - a04 = (state)->u.wide[20]; \ - a14 = (state)->u.wide[21]; \ - a24 = (state)->u.wide[22]; \ - a34 = (state)->u.wide[23]; \ - a44 = (state)->u.wide[24]; \ - } while (0) - -#define WRITE_STATE(state) do { \ - (state)->u.wide[ 0] = a00; \ - (state)->u.wide[ 1] = a10; \ - (state)->u.wide[ 2] = a20; \ - (state)->u.wide[ 3] = a30; \ - (state)->u.wide[ 4] = a40; \ - (state)->u.wide[ 5] = a01; \ - (state)->u.wide[ 6] = a11; \ - (state)->u.wide[ 7] = a21; \ - (state)->u.wide[ 8] = a31; \ - (state)->u.wide[ 9] = a41; \ - (state)->u.wide[10] = a02; \ - (state)->u.wide[11] = a12; \ - (state)->u.wide[12] = a22; \ - (state)->u.wide[13] = a32; \ - (state)->u.wide[14] = a42; \ - (state)->u.wide[15] = a03; \ - (state)->u.wide[16] = a13; \ - (state)->u.wide[17] = a23; \ - (state)->u.wide[18] = a33; \ - (state)->u.wide[19] = a43; \ - (state)->u.wide[20] = a04; \ - (state)->u.wide[21] = a14; \ - (state)->u.wide[22] = a24; \ - (state)->u.wide[23] = a34; \ - (state)->u.wide[24] = a44; \ - } while (0) - -#define INPUT_BUF144 do { \ - a00 ^= sph_dec64le_aligned(buf + 0); \ - a10 ^= sph_dec64le_aligned(buf + 8); \ - a20 ^= sph_dec64le_aligned(buf + 16); \ - a30 ^= sph_dec64le_aligned(buf + 24); \ - a40 ^= sph_dec64le_aligned(buf + 32); \ - a01 ^= sph_dec64le_aligned(buf + 40); \ - a11 ^= sph_dec64le_aligned(buf + 48); \ - a21 ^= sph_dec64le_aligned(buf + 56); \ - a31 ^= sph_dec64le_aligned(buf + 64); \ - a41 ^= sph_dec64le_aligned(buf + 72); \ - a02 ^= sph_dec64le_aligned(buf + 80); \ - a12 ^= sph_dec64le_aligned(buf + 88); \ - a22 ^= sph_dec64le_aligned(buf + 96); \ - a32 ^= sph_dec64le_aligned(buf + 104); \ - a42 ^= sph_dec64le_aligned(buf + 112); \ - a03 ^= sph_dec64le_aligned(buf + 120); \ - a13 ^= sph_dec64le_aligned(buf + 128); \ - a23 ^= sph_dec64le_aligned(buf + 136); \ - } while (0) - -#define INPUT_BUF136 do { \ - a00 ^= sph_dec64le_aligned(buf + 0); \ - a10 ^= sph_dec64le_aligned(buf + 8); \ - a20 ^= sph_dec64le_aligned(buf + 16); \ - a30 ^= sph_dec64le_aligned(buf + 24); \ - a40 ^= sph_dec64le_aligned(buf + 32); \ - a01 ^= sph_dec64le_aligned(buf + 40); \ - a11 ^= sph_dec64le_aligned(buf + 48); \ - a21 ^= sph_dec64le_aligned(buf + 56); \ - a31 ^= sph_dec64le_aligned(buf + 64); \ - a41 ^= sph_dec64le_aligned(buf + 72); \ - a02 ^= sph_dec64le_aligned(buf + 80); \ - a12 ^= sph_dec64le_aligned(buf + 88); \ - a22 ^= sph_dec64le_aligned(buf + 96); \ - a32 ^= sph_dec64le_aligned(buf + 104); \ - a42 ^= sph_dec64le_aligned(buf + 112); \ - a03 ^= sph_dec64le_aligned(buf + 120); \ - a13 ^= sph_dec64le_aligned(buf + 128); \ - } while (0) - -#define INPUT_BUF104 do { \ - a00 ^= sph_dec64le_aligned(buf + 0); \ - a10 ^= sph_dec64le_aligned(buf + 8); \ - a20 ^= sph_dec64le_aligned(buf + 16); \ - a30 ^= sph_dec64le_aligned(buf + 24); \ - a40 ^= sph_dec64le_aligned(buf + 32); \ - a01 ^= sph_dec64le_aligned(buf + 40); \ - a11 ^= sph_dec64le_aligned(buf + 48); \ - a21 ^= sph_dec64le_aligned(buf + 56); \ - a31 ^= sph_dec64le_aligned(buf + 64); \ - a41 ^= sph_dec64le_aligned(buf + 72); \ - a02 ^= sph_dec64le_aligned(buf + 80); \ - a12 ^= sph_dec64le_aligned(buf + 88); \ - a22 ^= sph_dec64le_aligned(buf + 96); \ - } while (0) - -#define INPUT_BUF72 do { \ - a00 ^= sph_dec64le_aligned(buf + 0); \ - a10 ^= sph_dec64le_aligned(buf + 8); \ - a20 ^= sph_dec64le_aligned(buf + 16); \ - a30 ^= sph_dec64le_aligned(buf + 24); \ - a40 ^= sph_dec64le_aligned(buf + 32); \ - a01 ^= sph_dec64le_aligned(buf + 40); \ - a11 ^= sph_dec64le_aligned(buf + 48); \ - a21 ^= sph_dec64le_aligned(buf + 56); \ - a31 ^= sph_dec64le_aligned(buf + 64); \ - } while (0) - -#define INPUT_BUF(lim) do { \ - a00 ^= sph_dec64le_aligned(buf + 0); \ - a10 ^= sph_dec64le_aligned(buf + 8); \ - a20 ^= sph_dec64le_aligned(buf + 16); \ - a30 ^= sph_dec64le_aligned(buf + 24); \ - a40 ^= sph_dec64le_aligned(buf + 32); \ - a01 ^= sph_dec64le_aligned(buf + 40); \ - a11 ^= sph_dec64le_aligned(buf + 48); \ - a21 ^= sph_dec64le_aligned(buf + 56); \ - a31 ^= sph_dec64le_aligned(buf + 64); \ - if ((lim) == 72) \ - break; \ - a41 ^= sph_dec64le_aligned(buf + 72); \ - a02 ^= sph_dec64le_aligned(buf + 80); \ - a12 ^= sph_dec64le_aligned(buf + 88); \ - a22 ^= sph_dec64le_aligned(buf + 96); \ - if ((lim) == 104) \ - break; \ - a32 ^= sph_dec64le_aligned(buf + 104); \ - a42 ^= sph_dec64le_aligned(buf + 112); \ - a03 ^= sph_dec64le_aligned(buf + 120); \ - a13 ^= sph_dec64le_aligned(buf + 128); \ - if ((lim) == 136) \ - break; \ - a23 ^= sph_dec64le_aligned(buf + 136); \ - } while (0) - -#endif - -#define DECL64(x) sph_u64 x -#define MOV64(d, s) (d = s) -#define XOR64(d, a, b) (d = a ^ b) -#define AND64(d, a, b) (d = a & b) -#define OR64(d, a, b) (d = a | b) -#define NOT64(d, s) (d = SPH_T64(~s)) -#define ROL64(d, v, n) (d = SPH_ROTL64(v, n)) -#define XOR64_IOTA XOR64 - -#else - -static const struct { - sph_u32 high, low; -} RC[] = { -#if SPH_KECCAK_INTERLEAVE - { SPH_C32(0x00000000), SPH_C32(0x00000001) }, - { SPH_C32(0x00000089), SPH_C32(0x00000000) }, - { SPH_C32(0x8000008B), SPH_C32(0x00000000) }, - { SPH_C32(0x80008080), SPH_C32(0x00000000) }, - { SPH_C32(0x0000008B), SPH_C32(0x00000001) }, - { SPH_C32(0x00008000), SPH_C32(0x00000001) }, - { SPH_C32(0x80008088), SPH_C32(0x00000001) }, - { SPH_C32(0x80000082), SPH_C32(0x00000001) }, - { SPH_C32(0x0000000B), SPH_C32(0x00000000) }, - { SPH_C32(0x0000000A), SPH_C32(0x00000000) }, - { SPH_C32(0x00008082), SPH_C32(0x00000001) }, - { SPH_C32(0x00008003), SPH_C32(0x00000000) }, - { SPH_C32(0x0000808B), SPH_C32(0x00000001) }, - { SPH_C32(0x8000000B), SPH_C32(0x00000001) }, - { SPH_C32(0x8000008A), SPH_C32(0x00000001) }, - { SPH_C32(0x80000081), SPH_C32(0x00000001) }, - { SPH_C32(0x80000081), SPH_C32(0x00000000) }, - { SPH_C32(0x80000008), SPH_C32(0x00000000) }, - { SPH_C32(0x00000083), SPH_C32(0x00000000) }, - { SPH_C32(0x80008003), SPH_C32(0x00000000) }, - { SPH_C32(0x80008088), SPH_C32(0x00000001) }, - { SPH_C32(0x80000088), SPH_C32(0x00000000) }, - { SPH_C32(0x00008000), SPH_C32(0x00000001) }, - { SPH_C32(0x80008082), SPH_C32(0x00000000) } -#else - { SPH_C32(0x00000000), SPH_C32(0x00000001) }, - { SPH_C32(0x00000000), SPH_C32(0x00008082) }, - { SPH_C32(0x80000000), SPH_C32(0x0000808A) }, - { SPH_C32(0x80000000), SPH_C32(0x80008000) }, - { SPH_C32(0x00000000), SPH_C32(0x0000808B) }, - { SPH_C32(0x00000000), SPH_C32(0x80000001) }, - { SPH_C32(0x80000000), SPH_C32(0x80008081) }, - { SPH_C32(0x80000000), SPH_C32(0x00008009) }, - { SPH_C32(0x00000000), SPH_C32(0x0000008A) }, - { SPH_C32(0x00000000), SPH_C32(0x00000088) }, - { SPH_C32(0x00000000), SPH_C32(0x80008009) }, - { SPH_C32(0x00000000), SPH_C32(0x8000000A) }, - { SPH_C32(0x00000000), SPH_C32(0x8000808B) }, - { SPH_C32(0x80000000), SPH_C32(0x0000008B) }, - { SPH_C32(0x80000000), SPH_C32(0x00008089) }, - { SPH_C32(0x80000000), SPH_C32(0x00008003) }, - { SPH_C32(0x80000000), SPH_C32(0x00008002) }, - { SPH_C32(0x80000000), SPH_C32(0x00000080) }, - { SPH_C32(0x00000000), SPH_C32(0x0000800A) }, - { SPH_C32(0x80000000), SPH_C32(0x8000000A) }, - { SPH_C32(0x80000000), SPH_C32(0x80008081) }, - { SPH_C32(0x80000000), SPH_C32(0x00008080) }, - { SPH_C32(0x00000000), SPH_C32(0x80000001) }, - { SPH_C32(0x80000000), SPH_C32(0x80008008) } -#endif -}; - -#if SPH_KECCAK_INTERLEAVE - -#define INTERLEAVE(xl, xh) do { \ - sph_u32 l, h, t; \ - l = (xl); h = (xh); \ - t = (l ^ (l >> 1)) & SPH_C32(0x22222222); l ^= t ^ (t << 1); \ - t = (h ^ (h >> 1)) & SPH_C32(0x22222222); h ^= t ^ (t << 1); \ - t = (l ^ (l >> 2)) & SPH_C32(0x0C0C0C0C); l ^= t ^ (t << 2); \ - t = (h ^ (h >> 2)) & SPH_C32(0x0C0C0C0C); h ^= t ^ (t << 2); \ - t = (l ^ (l >> 4)) & SPH_C32(0x00F000F0); l ^= t ^ (t << 4); \ - t = (h ^ (h >> 4)) & SPH_C32(0x00F000F0); h ^= t ^ (t << 4); \ - t = (l ^ (l >> 8)) & SPH_C32(0x0000FF00); l ^= t ^ (t << 8); \ - t = (h ^ (h >> 8)) & SPH_C32(0x0000FF00); h ^= t ^ (t << 8); \ - t = (l ^ SPH_T32(h << 16)) & SPH_C32(0xFFFF0000); \ - l ^= t; h ^= t >> 16; \ - (xl) = l; (xh) = h; \ - } while (0) - -#define UNINTERLEAVE(xl, xh) do { \ - sph_u32 l, h, t; \ - l = (xl); h = (xh); \ - t = (l ^ SPH_T32(h << 16)) & SPH_C32(0xFFFF0000); \ - l ^= t; h ^= t >> 16; \ - t = (l ^ (l >> 8)) & SPH_C32(0x0000FF00); l ^= t ^ (t << 8); \ - t = (h ^ (h >> 8)) & SPH_C32(0x0000FF00); h ^= t ^ (t << 8); \ - t = (l ^ (l >> 4)) & SPH_C32(0x00F000F0); l ^= t ^ (t << 4); \ - t = (h ^ (h >> 4)) & SPH_C32(0x00F000F0); h ^= t ^ (t << 4); \ - t = (l ^ (l >> 2)) & SPH_C32(0x0C0C0C0C); l ^= t ^ (t << 2); \ - t = (h ^ (h >> 2)) & SPH_C32(0x0C0C0C0C); h ^= t ^ (t << 2); \ - t = (l ^ (l >> 1)) & SPH_C32(0x22222222); l ^= t ^ (t << 1); \ - t = (h ^ (h >> 1)) & SPH_C32(0x22222222); h ^= t ^ (t << 1); \ - (xl) = l; (xh) = h; \ - } while (0) - -#else - -#define INTERLEAVE(l, h) -#define UNINTERLEAVE(l, h) - -#endif - -#if SPH_KECCAK_NOCOPY - -#define a00l (kc->u.narrow[2 * 0 + 0]) -#define a00h (kc->u.narrow[2 * 0 + 1]) -#define a10l (kc->u.narrow[2 * 1 + 0]) -#define a10h (kc->u.narrow[2 * 1 + 1]) -#define a20l (kc->u.narrow[2 * 2 + 0]) -#define a20h (kc->u.narrow[2 * 2 + 1]) -#define a30l (kc->u.narrow[2 * 3 + 0]) -#define a30h (kc->u.narrow[2 * 3 + 1]) -#define a40l (kc->u.narrow[2 * 4 + 0]) -#define a40h (kc->u.narrow[2 * 4 + 1]) -#define a01l (kc->u.narrow[2 * 5 + 0]) -#define a01h (kc->u.narrow[2 * 5 + 1]) -#define a11l (kc->u.narrow[2 * 6 + 0]) -#define a11h (kc->u.narrow[2 * 6 + 1]) -#define a21l (kc->u.narrow[2 * 7 + 0]) -#define a21h (kc->u.narrow[2 * 7 + 1]) -#define a31l (kc->u.narrow[2 * 8 + 0]) -#define a31h (kc->u.narrow[2 * 8 + 1]) -#define a41l (kc->u.narrow[2 * 9 + 0]) -#define a41h (kc->u.narrow[2 * 9 + 1]) -#define a02l (kc->u.narrow[2 * 10 + 0]) -#define a02h (kc->u.narrow[2 * 10 + 1]) -#define a12l (kc->u.narrow[2 * 11 + 0]) -#define a12h (kc->u.narrow[2 * 11 + 1]) -#define a22l (kc->u.narrow[2 * 12 + 0]) -#define a22h (kc->u.narrow[2 * 12 + 1]) -#define a32l (kc->u.narrow[2 * 13 + 0]) -#define a32h (kc->u.narrow[2 * 13 + 1]) -#define a42l (kc->u.narrow[2 * 14 + 0]) -#define a42h (kc->u.narrow[2 * 14 + 1]) -#define a03l (kc->u.narrow[2 * 15 + 0]) -#define a03h (kc->u.narrow[2 * 15 + 1]) -#define a13l (kc->u.narrow[2 * 16 + 0]) -#define a13h (kc->u.narrow[2 * 16 + 1]) -#define a23l (kc->u.narrow[2 * 17 + 0]) -#define a23h (kc->u.narrow[2 * 17 + 1]) -#define a33l (kc->u.narrow[2 * 18 + 0]) -#define a33h (kc->u.narrow[2 * 18 + 1]) -#define a43l (kc->u.narrow[2 * 19 + 0]) -#define a43h (kc->u.narrow[2 * 19 + 1]) -#define a04l (kc->u.narrow[2 * 20 + 0]) -#define a04h (kc->u.narrow[2 * 20 + 1]) -#define a14l (kc->u.narrow[2 * 21 + 0]) -#define a14h (kc->u.narrow[2 * 21 + 1]) -#define a24l (kc->u.narrow[2 * 22 + 0]) -#define a24h (kc->u.narrow[2 * 22 + 1]) -#define a34l (kc->u.narrow[2 * 23 + 0]) -#define a34h (kc->u.narrow[2 * 23 + 1]) -#define a44l (kc->u.narrow[2 * 24 + 0]) -#define a44h (kc->u.narrow[2 * 24 + 1]) - -#define DECL_STATE -#define READ_STATE(state) -#define WRITE_STATE(state) - -#define INPUT_BUF(size) do { \ - size_t j; \ - for (j = 0; j < (size); j += 8) { \ - sph_u32 tl, th; \ - tl = sph_dec32le_aligned(buf + j + 0); \ - th = sph_dec32le_aligned(buf + j + 4); \ - INTERLEAVE(tl, th); \ - kc->u.narrow[(j >> 2) + 0] ^= tl; \ - kc->u.narrow[(j >> 2) + 1] ^= th; \ - } \ - } while (0) - -#define INPUT_BUF144 INPUT_BUF(144) -#define INPUT_BUF136 INPUT_BUF(136) -#define INPUT_BUF104 INPUT_BUF(104) -#define INPUT_BUF72 INPUT_BUF(72) - -#else - -#define DECL_STATE \ - sph_u32 a00l, a00h, a01l, a01h, a02l, a02h, a03l, a03h, a04l, a04h; \ - sph_u32 a10l, a10h, a11l, a11h, a12l, a12h, a13l, a13h, a14l, a14h; \ - sph_u32 a20l, a20h, a21l, a21h, a22l, a22h, a23l, a23h, a24l, a24h; \ - sph_u32 a30l, a30h, a31l, a31h, a32l, a32h, a33l, a33h, a34l, a34h; \ - sph_u32 a40l, a40h, a41l, a41h, a42l, a42h, a43l, a43h, a44l, a44h; - -#define READ_STATE(state) do { \ - a00l = (state)->u.narrow[2 * 0 + 0]; \ - a00h = (state)->u.narrow[2 * 0 + 1]; \ - a10l = (state)->u.narrow[2 * 1 + 0]; \ - a10h = (state)->u.narrow[2 * 1 + 1]; \ - a20l = (state)->u.narrow[2 * 2 + 0]; \ - a20h = (state)->u.narrow[2 * 2 + 1]; \ - a30l = (state)->u.narrow[2 * 3 + 0]; \ - a30h = (state)->u.narrow[2 * 3 + 1]; \ - a40l = (state)->u.narrow[2 * 4 + 0]; \ - a40h = (state)->u.narrow[2 * 4 + 1]; \ - a01l = (state)->u.narrow[2 * 5 + 0]; \ - a01h = (state)->u.narrow[2 * 5 + 1]; \ - a11l = (state)->u.narrow[2 * 6 + 0]; \ - a11h = (state)->u.narrow[2 * 6 + 1]; \ - a21l = (state)->u.narrow[2 * 7 + 0]; \ - a21h = (state)->u.narrow[2 * 7 + 1]; \ - a31l = (state)->u.narrow[2 * 8 + 0]; \ - a31h = (state)->u.narrow[2 * 8 + 1]; \ - a41l = (state)->u.narrow[2 * 9 + 0]; \ - a41h = (state)->u.narrow[2 * 9 + 1]; \ - a02l = (state)->u.narrow[2 * 10 + 0]; \ - a02h = (state)->u.narrow[2 * 10 + 1]; \ - a12l = (state)->u.narrow[2 * 11 + 0]; \ - a12h = (state)->u.narrow[2 * 11 + 1]; \ - a22l = (state)->u.narrow[2 * 12 + 0]; \ - a22h = (state)->u.narrow[2 * 12 + 1]; \ - a32l = (state)->u.narrow[2 * 13 + 0]; \ - a32h = (state)->u.narrow[2 * 13 + 1]; \ - a42l = (state)->u.narrow[2 * 14 + 0]; \ - a42h = (state)->u.narrow[2 * 14 + 1]; \ - a03l = (state)->u.narrow[2 * 15 + 0]; \ - a03h = (state)->u.narrow[2 * 15 + 1]; \ - a13l = (state)->u.narrow[2 * 16 + 0]; \ - a13h = (state)->u.narrow[2 * 16 + 1]; \ - a23l = (state)->u.narrow[2 * 17 + 0]; \ - a23h = (state)->u.narrow[2 * 17 + 1]; \ - a33l = (state)->u.narrow[2 * 18 + 0]; \ - a33h = (state)->u.narrow[2 * 18 + 1]; \ - a43l = (state)->u.narrow[2 * 19 + 0]; \ - a43h = (state)->u.narrow[2 * 19 + 1]; \ - a04l = (state)->u.narrow[2 * 20 + 0]; \ - a04h = (state)->u.narrow[2 * 20 + 1]; \ - a14l = (state)->u.narrow[2 * 21 + 0]; \ - a14h = (state)->u.narrow[2 * 21 + 1]; \ - a24l = (state)->u.narrow[2 * 22 + 0]; \ - a24h = (state)->u.narrow[2 * 22 + 1]; \ - a34l = (state)->u.narrow[2 * 23 + 0]; \ - a34h = (state)->u.narrow[2 * 23 + 1]; \ - a44l = (state)->u.narrow[2 * 24 + 0]; \ - a44h = (state)->u.narrow[2 * 24 + 1]; \ - } while (0) - -#define WRITE_STATE(state) do { \ - (state)->u.narrow[2 * 0 + 0] = a00l; \ - (state)->u.narrow[2 * 0 + 1] = a00h; \ - (state)->u.narrow[2 * 1 + 0] = a10l; \ - (state)->u.narrow[2 * 1 + 1] = a10h; \ - (state)->u.narrow[2 * 2 + 0] = a20l; \ - (state)->u.narrow[2 * 2 + 1] = a20h; \ - (state)->u.narrow[2 * 3 + 0] = a30l; \ - (state)->u.narrow[2 * 3 + 1] = a30h; \ - (state)->u.narrow[2 * 4 + 0] = a40l; \ - (state)->u.narrow[2 * 4 + 1] = a40h; \ - (state)->u.narrow[2 * 5 + 0] = a01l; \ - (state)->u.narrow[2 * 5 + 1] = a01h; \ - (state)->u.narrow[2 * 6 + 0] = a11l; \ - (state)->u.narrow[2 * 6 + 1] = a11h; \ - (state)->u.narrow[2 * 7 + 0] = a21l; \ - (state)->u.narrow[2 * 7 + 1] = a21h; \ - (state)->u.narrow[2 * 8 + 0] = a31l; \ - (state)->u.narrow[2 * 8 + 1] = a31h; \ - (state)->u.narrow[2 * 9 + 0] = a41l; \ - (state)->u.narrow[2 * 9 + 1] = a41h; \ - (state)->u.narrow[2 * 10 + 0] = a02l; \ - (state)->u.narrow[2 * 10 + 1] = a02h; \ - (state)->u.narrow[2 * 11 + 0] = a12l; \ - (state)->u.narrow[2 * 11 + 1] = a12h; \ - (state)->u.narrow[2 * 12 + 0] = a22l; \ - (state)->u.narrow[2 * 12 + 1] = a22h; \ - (state)->u.narrow[2 * 13 + 0] = a32l; \ - (state)->u.narrow[2 * 13 + 1] = a32h; \ - (state)->u.narrow[2 * 14 + 0] = a42l; \ - (state)->u.narrow[2 * 14 + 1] = a42h; \ - (state)->u.narrow[2 * 15 + 0] = a03l; \ - (state)->u.narrow[2 * 15 + 1] = a03h; \ - (state)->u.narrow[2 * 16 + 0] = a13l; \ - (state)->u.narrow[2 * 16 + 1] = a13h; \ - (state)->u.narrow[2 * 17 + 0] = a23l; \ - (state)->u.narrow[2 * 17 + 1] = a23h; \ - (state)->u.narrow[2 * 18 + 0] = a33l; \ - (state)->u.narrow[2 * 18 + 1] = a33h; \ - (state)->u.narrow[2 * 19 + 0] = a43l; \ - (state)->u.narrow[2 * 19 + 1] = a43h; \ - (state)->u.narrow[2 * 20 + 0] = a04l; \ - (state)->u.narrow[2 * 20 + 1] = a04h; \ - (state)->u.narrow[2 * 21 + 0] = a14l; \ - (state)->u.narrow[2 * 21 + 1] = a14h; \ - (state)->u.narrow[2 * 22 + 0] = a24l; \ - (state)->u.narrow[2 * 22 + 1] = a24h; \ - (state)->u.narrow[2 * 23 + 0] = a34l; \ - (state)->u.narrow[2 * 23 + 1] = a34h; \ - (state)->u.narrow[2 * 24 + 0] = a44l; \ - (state)->u.narrow[2 * 24 + 1] = a44h; \ - } while (0) - -#define READ64(d, off) do { \ - sph_u32 tl, th; \ - tl = sph_dec32le_aligned(buf + (off)); \ - th = sph_dec32le_aligned(buf + (off) + 4); \ - INTERLEAVE(tl, th); \ - d ## l ^= tl; \ - d ## h ^= th; \ - } while (0) - -#define INPUT_BUF144 do { \ - READ64(a00, 0); \ - READ64(a10, 8); \ - READ64(a20, 16); \ - READ64(a30, 24); \ - READ64(a40, 32); \ - READ64(a01, 40); \ - READ64(a11, 48); \ - READ64(a21, 56); \ - READ64(a31, 64); \ - READ64(a41, 72); \ - READ64(a02, 80); \ - READ64(a12, 88); \ - READ64(a22, 96); \ - READ64(a32, 104); \ - READ64(a42, 112); \ - READ64(a03, 120); \ - READ64(a13, 128); \ - READ64(a23, 136); \ - } while (0) - -#define INPUT_BUF136 do { \ - READ64(a00, 0); \ - READ64(a10, 8); \ - READ64(a20, 16); \ - READ64(a30, 24); \ - READ64(a40, 32); \ - READ64(a01, 40); \ - READ64(a11, 48); \ - READ64(a21, 56); \ - READ64(a31, 64); \ - READ64(a41, 72); \ - READ64(a02, 80); \ - READ64(a12, 88); \ - READ64(a22, 96); \ - READ64(a32, 104); \ - READ64(a42, 112); \ - READ64(a03, 120); \ - READ64(a13, 128); \ - } while (0) - -#define INPUT_BUF104 do { \ - READ64(a00, 0); \ - READ64(a10, 8); \ - READ64(a20, 16); \ - READ64(a30, 24); \ - READ64(a40, 32); \ - READ64(a01, 40); \ - READ64(a11, 48); \ - READ64(a21, 56); \ - READ64(a31, 64); \ - READ64(a41, 72); \ - READ64(a02, 80); \ - READ64(a12, 88); \ - READ64(a22, 96); \ - } while (0) - -#define INPUT_BUF72 do { \ - READ64(a00, 0); \ - READ64(a10, 8); \ - READ64(a20, 16); \ - READ64(a30, 24); \ - READ64(a40, 32); \ - READ64(a01, 40); \ - READ64(a11, 48); \ - READ64(a21, 56); \ - READ64(a31, 64); \ - } while (0) - -#define INPUT_BUF(lim) do { \ - READ64(a00, 0); \ - READ64(a10, 8); \ - READ64(a20, 16); \ - READ64(a30, 24); \ - READ64(a40, 32); \ - READ64(a01, 40); \ - READ64(a11, 48); \ - READ64(a21, 56); \ - READ64(a31, 64); \ - if ((lim) == 72) \ - break; \ - READ64(a41, 72); \ - READ64(a02, 80); \ - READ64(a12, 88); \ - READ64(a22, 96); \ - if ((lim) == 104) \ - break; \ - READ64(a32, 104); \ - READ64(a42, 112); \ - READ64(a03, 120); \ - READ64(a13, 128); \ - if ((lim) == 136) \ - break; \ - READ64(a23, 136); \ - } while (0) - -#endif - -#define DECL64(x) sph_u64 x ## l, x ## h -#define MOV64(d, s) (d ## l = s ## l, d ## h = s ## h) -#define XOR64(d, a, b) (d ## l = a ## l ^ b ## l, d ## h = a ## h ^ b ## h) -#define AND64(d, a, b) (d ## l = a ## l & b ## l, d ## h = a ## h & b ## h) -#define OR64(d, a, b) (d ## l = a ## l | b ## l, d ## h = a ## h | b ## h) -#define NOT64(d, s) (d ## l = SPH_T32(~s ## l), d ## h = SPH_T32(~s ## h)) -#define ROL64(d, v, n) ROL64_ ## n(d, v) - -#if SPH_KECCAK_INTERLEAVE - -#define ROL64_odd1(d, v) do { \ - sph_u32 tmp; \ - tmp = v ## l; \ - d ## l = SPH_T32(v ## h << 1) | (v ## h >> 31); \ - d ## h = tmp; \ - } while (0) - -#define ROL64_odd63(d, v) do { \ - sph_u32 tmp; \ - tmp = SPH_T32(v ## l << 31) | (v ## l >> 1); \ - d ## l = v ## h; \ - d ## h = tmp; \ - } while (0) - -#define ROL64_odd(d, v, n) do { \ - sph_u32 tmp; \ - tmp = SPH_T32(v ## l << (n - 1)) | (v ## l >> (33 - n)); \ - d ## l = SPH_T32(v ## h << n) | (v ## h >> (32 - n)); \ - d ## h = tmp; \ - } while (0) - -#define ROL64_even(d, v, n) do { \ - d ## l = SPH_T32(v ## l << n) | (v ## l >> (32 - n)); \ - d ## h = SPH_T32(v ## h << n) | (v ## h >> (32 - n)); \ - } while (0) - -#define ROL64_0(d, v) -#define ROL64_1(d, v) ROL64_odd1(d, v) -#define ROL64_2(d, v) ROL64_even(d, v, 1) -#define ROL64_3(d, v) ROL64_odd( d, v, 2) -#define ROL64_4(d, v) ROL64_even(d, v, 2) -#define ROL64_5(d, v) ROL64_odd( d, v, 3) -#define ROL64_6(d, v) ROL64_even(d, v, 3) -#define ROL64_7(d, v) ROL64_odd( d, v, 4) -#define ROL64_8(d, v) ROL64_even(d, v, 4) -#define ROL64_9(d, v) ROL64_odd( d, v, 5) -#define ROL64_10(d, v) ROL64_even(d, v, 5) -#define ROL64_11(d, v) ROL64_odd( d, v, 6) -#define ROL64_12(d, v) ROL64_even(d, v, 6) -#define ROL64_13(d, v) ROL64_odd( d, v, 7) -#define ROL64_14(d, v) ROL64_even(d, v, 7) -#define ROL64_15(d, v) ROL64_odd( d, v, 8) -#define ROL64_16(d, v) ROL64_even(d, v, 8) -#define ROL64_17(d, v) ROL64_odd( d, v, 9) -#define ROL64_18(d, v) ROL64_even(d, v, 9) -#define ROL64_19(d, v) ROL64_odd( d, v, 10) -#define ROL64_20(d, v) ROL64_even(d, v, 10) -#define ROL64_21(d, v) ROL64_odd( d, v, 11) -#define ROL64_22(d, v) ROL64_even(d, v, 11) -#define ROL64_23(d, v) ROL64_odd( d, v, 12) -#define ROL64_24(d, v) ROL64_even(d, v, 12) -#define ROL64_25(d, v) ROL64_odd( d, v, 13) -#define ROL64_26(d, v) ROL64_even(d, v, 13) -#define ROL64_27(d, v) ROL64_odd( d, v, 14) -#define ROL64_28(d, v) ROL64_even(d, v, 14) -#define ROL64_29(d, v) ROL64_odd( d, v, 15) -#define ROL64_30(d, v) ROL64_even(d, v, 15) -#define ROL64_31(d, v) ROL64_odd( d, v, 16) -#define ROL64_32(d, v) ROL64_even(d, v, 16) -#define ROL64_33(d, v) ROL64_odd( d, v, 17) -#define ROL64_34(d, v) ROL64_even(d, v, 17) -#define ROL64_35(d, v) ROL64_odd( d, v, 18) -#define ROL64_36(d, v) ROL64_even(d, v, 18) -#define ROL64_37(d, v) ROL64_odd( d, v, 19) -#define ROL64_38(d, v) ROL64_even(d, v, 19) -#define ROL64_39(d, v) ROL64_odd( d, v, 20) -#define ROL64_40(d, v) ROL64_even(d, v, 20) -#define ROL64_41(d, v) ROL64_odd( d, v, 21) -#define ROL64_42(d, v) ROL64_even(d, v, 21) -#define ROL64_43(d, v) ROL64_odd( d, v, 22) -#define ROL64_44(d, v) ROL64_even(d, v, 22) -#define ROL64_45(d, v) ROL64_odd( d, v, 23) -#define ROL64_46(d, v) ROL64_even(d, v, 23) -#define ROL64_47(d, v) ROL64_odd( d, v, 24) -#define ROL64_48(d, v) ROL64_even(d, v, 24) -#define ROL64_49(d, v) ROL64_odd( d, v, 25) -#define ROL64_50(d, v) ROL64_even(d, v, 25) -#define ROL64_51(d, v) ROL64_odd( d, v, 26) -#define ROL64_52(d, v) ROL64_even(d, v, 26) -#define ROL64_53(d, v) ROL64_odd( d, v, 27) -#define ROL64_54(d, v) ROL64_even(d, v, 27) -#define ROL64_55(d, v) ROL64_odd( d, v, 28) -#define ROL64_56(d, v) ROL64_even(d, v, 28) -#define ROL64_57(d, v) ROL64_odd( d, v, 29) -#define ROL64_58(d, v) ROL64_even(d, v, 29) -#define ROL64_59(d, v) ROL64_odd( d, v, 30) -#define ROL64_60(d, v) ROL64_even(d, v, 30) -#define ROL64_61(d, v) ROL64_odd( d, v, 31) -#define ROL64_62(d, v) ROL64_even(d, v, 31) -#define ROL64_63(d, v) ROL64_odd63(d, v) - -#else - -#define ROL64_small(d, v, n) do { \ - sph_u32 tmp; \ - tmp = SPH_T32(v ## l << n) | (v ## h >> (32 - n)); \ - d ## h = SPH_T32(v ## h << n) | (v ## l >> (32 - n)); \ - d ## l = tmp; \ - } while (0) - -#define ROL64_0(d, v) 0 -#define ROL64_1(d, v) ROL64_small(d, v, 1) -#define ROL64_2(d, v) ROL64_small(d, v, 2) -#define ROL64_3(d, v) ROL64_small(d, v, 3) -#define ROL64_4(d, v) ROL64_small(d, v, 4) -#define ROL64_5(d, v) ROL64_small(d, v, 5) -#define ROL64_6(d, v) ROL64_small(d, v, 6) -#define ROL64_7(d, v) ROL64_small(d, v, 7) -#define ROL64_8(d, v) ROL64_small(d, v, 8) -#define ROL64_9(d, v) ROL64_small(d, v, 9) -#define ROL64_10(d, v) ROL64_small(d, v, 10) -#define ROL64_11(d, v) ROL64_small(d, v, 11) -#define ROL64_12(d, v) ROL64_small(d, v, 12) -#define ROL64_13(d, v) ROL64_small(d, v, 13) -#define ROL64_14(d, v) ROL64_small(d, v, 14) -#define ROL64_15(d, v) ROL64_small(d, v, 15) -#define ROL64_16(d, v) ROL64_small(d, v, 16) -#define ROL64_17(d, v) ROL64_small(d, v, 17) -#define ROL64_18(d, v) ROL64_small(d, v, 18) -#define ROL64_19(d, v) ROL64_small(d, v, 19) -#define ROL64_20(d, v) ROL64_small(d, v, 20) -#define ROL64_21(d, v) ROL64_small(d, v, 21) -#define ROL64_22(d, v) ROL64_small(d, v, 22) -#define ROL64_23(d, v) ROL64_small(d, v, 23) -#define ROL64_24(d, v) ROL64_small(d, v, 24) -#define ROL64_25(d, v) ROL64_small(d, v, 25) -#define ROL64_26(d, v) ROL64_small(d, v, 26) -#define ROL64_27(d, v) ROL64_small(d, v, 27) -#define ROL64_28(d, v) ROL64_small(d, v, 28) -#define ROL64_29(d, v) ROL64_small(d, v, 29) -#define ROL64_30(d, v) ROL64_small(d, v, 30) -#define ROL64_31(d, v) ROL64_small(d, v, 31) - -#define ROL64_32(d, v) do { \ - sph_u32 tmp; \ - tmp = v ## l; \ - d ## l = v ## h; \ - d ## h = tmp; \ - } while (0) - -#define ROL64_big(d, v, n) do { \ - sph_u32 trl, trh; \ - ROL64_small(tr, v, n); \ - d ## h = trl; \ - d ## l = trh; \ - } while (0) - -#define ROL64_33(d, v) ROL64_big(d, v, 1) -#define ROL64_34(d, v) ROL64_big(d, v, 2) -#define ROL64_35(d, v) ROL64_big(d, v, 3) -#define ROL64_36(d, v) ROL64_big(d, v, 4) -#define ROL64_37(d, v) ROL64_big(d, v, 5) -#define ROL64_38(d, v) ROL64_big(d, v, 6) -#define ROL64_39(d, v) ROL64_big(d, v, 7) -#define ROL64_40(d, v) ROL64_big(d, v, 8) -#define ROL64_41(d, v) ROL64_big(d, v, 9) -#define ROL64_42(d, v) ROL64_big(d, v, 10) -#define ROL64_43(d, v) ROL64_big(d, v, 11) -#define ROL64_44(d, v) ROL64_big(d, v, 12) -#define ROL64_45(d, v) ROL64_big(d, v, 13) -#define ROL64_46(d, v) ROL64_big(d, v, 14) -#define ROL64_47(d, v) ROL64_big(d, v, 15) -#define ROL64_48(d, v) ROL64_big(d, v, 16) -#define ROL64_49(d, v) ROL64_big(d, v, 17) -#define ROL64_50(d, v) ROL64_big(d, v, 18) -#define ROL64_51(d, v) ROL64_big(d, v, 19) -#define ROL64_52(d, v) ROL64_big(d, v, 20) -#define ROL64_53(d, v) ROL64_big(d, v, 21) -#define ROL64_54(d, v) ROL64_big(d, v, 22) -#define ROL64_55(d, v) ROL64_big(d, v, 23) -#define ROL64_56(d, v) ROL64_big(d, v, 24) -#define ROL64_57(d, v) ROL64_big(d, v, 25) -#define ROL64_58(d, v) ROL64_big(d, v, 26) -#define ROL64_59(d, v) ROL64_big(d, v, 27) -#define ROL64_60(d, v) ROL64_big(d, v, 28) -#define ROL64_61(d, v) ROL64_big(d, v, 29) -#define ROL64_62(d, v) ROL64_big(d, v, 30) -#define ROL64_63(d, v) ROL64_big(d, v, 31) - -#endif - -#define XOR64_IOTA(d, s, k) \ - (d ## l = s ## l ^ k.low, d ## h = s ## h ^ k.high) - -#endif - -#define TH_ELT(t, c0, c1, c2, c3, c4, d0, d1, d2, d3, d4) do { \ - DECL64(tt0); \ - DECL64(tt1); \ - DECL64(tt2); \ - DECL64(tt3); \ - XOR64(tt0, d0, d1); \ - XOR64(tt1, d2, d3); \ - XOR64(tt0, tt0, d4); \ - XOR64(tt0, tt0, tt1); \ - ROL64(tt0, tt0, 1); \ - XOR64(tt2, c0, c1); \ - XOR64(tt3, c2, c3); \ - XOR64(tt0, tt0, c4); \ - XOR64(tt2, tt2, tt3); \ - XOR64(t, tt0, tt2); \ - } while (0) - -#define THETA(b00, b01, b02, b03, b04, b10, b11, b12, b13, b14, \ - b20, b21, b22, b23, b24, b30, b31, b32, b33, b34, \ - b40, b41, b42, b43, b44) \ - do { \ - DECL64(t0); \ - DECL64(t1); \ - DECL64(t2); \ - DECL64(t3); \ - DECL64(t4); \ - TH_ELT(t0, b40, b41, b42, b43, b44, b10, b11, b12, b13, b14); \ - TH_ELT(t1, b00, b01, b02, b03, b04, b20, b21, b22, b23, b24); \ - TH_ELT(t2, b10, b11, b12, b13, b14, b30, b31, b32, b33, b34); \ - TH_ELT(t3, b20, b21, b22, b23, b24, b40, b41, b42, b43, b44); \ - TH_ELT(t4, b30, b31, b32, b33, b34, b00, b01, b02, b03, b04); \ - XOR64(b00, b00, t0); \ - XOR64(b01, b01, t0); \ - XOR64(b02, b02, t0); \ - XOR64(b03, b03, t0); \ - XOR64(b04, b04, t0); \ - XOR64(b10, b10, t1); \ - XOR64(b11, b11, t1); \ - XOR64(b12, b12, t1); \ - XOR64(b13, b13, t1); \ - XOR64(b14, b14, t1); \ - XOR64(b20, b20, t2); \ - XOR64(b21, b21, t2); \ - XOR64(b22, b22, t2); \ - XOR64(b23, b23, t2); \ - XOR64(b24, b24, t2); \ - XOR64(b30, b30, t3); \ - XOR64(b31, b31, t3); \ - XOR64(b32, b32, t3); \ - XOR64(b33, b33, t3); \ - XOR64(b34, b34, t3); \ - XOR64(b40, b40, t4); \ - XOR64(b41, b41, t4); \ - XOR64(b42, b42, t4); \ - XOR64(b43, b43, t4); \ - XOR64(b44, b44, t4); \ - } while (0) - -#define RHO(b00, b01, b02, b03, b04, b10, b11, b12, b13, b14, \ - b20, b21, b22, b23, b24, b30, b31, b32, b33, b34, \ - b40, b41, b42, b43, b44) \ - do { \ - /* ROL64(b00, b00, 0); */ \ - ROL64(b01, b01, 36); \ - ROL64(b02, b02, 3); \ - ROL64(b03, b03, 41); \ - ROL64(b04, b04, 18); \ - ROL64(b10, b10, 1); \ - ROL64(b11, b11, 44); \ - ROL64(b12, b12, 10); \ - ROL64(b13, b13, 45); \ - ROL64(b14, b14, 2); \ - ROL64(b20, b20, 62); \ - ROL64(b21, b21, 6); \ - ROL64(b22, b22, 43); \ - ROL64(b23, b23, 15); \ - ROL64(b24, b24, 61); \ - ROL64(b30, b30, 28); \ - ROL64(b31, b31, 55); \ - ROL64(b32, b32, 25); \ - ROL64(b33, b33, 21); \ - ROL64(b34, b34, 56); \ - ROL64(b40, b40, 27); \ - ROL64(b41, b41, 20); \ - ROL64(b42, b42, 39); \ - ROL64(b43, b43, 8); \ - ROL64(b44, b44, 14); \ - } while (0) - -/* - * The KHI macro integrates the "lane complement" optimization. On input, - * some words are complemented: - * a00 a01 a02 a04 a13 a20 a21 a22 a30 a33 a34 a43 - * On output, the following words are complemented: - * a04 a10 a20 a22 a23 a31 - * - * The (implicit) permutation and the theta expansion will bring back - * the input mask for the next round. - */ - -#define KHI_XO(d, a, b, c) do { \ - DECL64(kt); \ - OR64(kt, b, c); \ - XOR64(d, a, kt); \ - } while (0) - -#define KHI_XA(d, a, b, c) do { \ - DECL64(kt); \ - AND64(kt, b, c); \ - XOR64(d, a, kt); \ - } while (0) - -#define KHI(b00, b01, b02, b03, b04, b10, b11, b12, b13, b14, \ - b20, b21, b22, b23, b24, b30, b31, b32, b33, b34, \ - b40, b41, b42, b43, b44) \ - do { \ - DECL64(c0); \ - DECL64(c1); \ - DECL64(c2); \ - DECL64(c3); \ - DECL64(c4); \ - DECL64(bnn); \ - NOT64(bnn, b20); \ - KHI_XO(c0, b00, b10, b20); \ - KHI_XO(c1, b10, bnn, b30); \ - KHI_XA(c2, b20, b30, b40); \ - KHI_XO(c3, b30, b40, b00); \ - KHI_XA(c4, b40, b00, b10); \ - MOV64(b00, c0); \ - MOV64(b10, c1); \ - MOV64(b20, c2); \ - MOV64(b30, c3); \ - MOV64(b40, c4); \ - NOT64(bnn, b41); \ - KHI_XO(c0, b01, b11, b21); \ - KHI_XA(c1, b11, b21, b31); \ - KHI_XO(c2, b21, b31, bnn); \ - KHI_XO(c3, b31, b41, b01); \ - KHI_XA(c4, b41, b01, b11); \ - MOV64(b01, c0); \ - MOV64(b11, c1); \ - MOV64(b21, c2); \ - MOV64(b31, c3); \ - MOV64(b41, c4); \ - NOT64(bnn, b32); \ - KHI_XO(c0, b02, b12, b22); \ - KHI_XA(c1, b12, b22, b32); \ - KHI_XA(c2, b22, bnn, b42); \ - KHI_XO(c3, bnn, b42, b02); \ - KHI_XA(c4, b42, b02, b12); \ - MOV64(b02, c0); \ - MOV64(b12, c1); \ - MOV64(b22, c2); \ - MOV64(b32, c3); \ - MOV64(b42, c4); \ - NOT64(bnn, b33); \ - KHI_XA(c0, b03, b13, b23); \ - KHI_XO(c1, b13, b23, b33); \ - KHI_XO(c2, b23, bnn, b43); \ - KHI_XA(c3, bnn, b43, b03); \ - KHI_XO(c4, b43, b03, b13); \ - MOV64(b03, c0); \ - MOV64(b13, c1); \ - MOV64(b23, c2); \ - MOV64(b33, c3); \ - MOV64(b43, c4); \ - NOT64(bnn, b14); \ - KHI_XA(c0, b04, bnn, b24); \ - KHI_XO(c1, bnn, b24, b34); \ - KHI_XA(c2, b24, b34, b44); \ - KHI_XO(c3, b34, b44, b04); \ - KHI_XA(c4, b44, b04, b14); \ - MOV64(b04, c0); \ - MOV64(b14, c1); \ - MOV64(b24, c2); \ - MOV64(b34, c3); \ - MOV64(b44, c4); \ - } while (0) - -#define IOTA(r) XOR64_IOTA(a00, a00, r) - -#define P0 a00, a01, a02, a03, a04, a10, a11, a12, a13, a14, a20, a21, \ - a22, a23, a24, a30, a31, a32, a33, a34, a40, a41, a42, a43, a44 -#define P1 a00, a30, a10, a40, a20, a11, a41, a21, a01, a31, a22, a02, \ - a32, a12, a42, a33, a13, a43, a23, a03, a44, a24, a04, a34, a14 -#define P2 a00, a33, a11, a44, a22, a41, a24, a02, a30, a13, a32, a10, \ - a43, a21, a04, a23, a01, a34, a12, a40, a14, a42, a20, a03, a31 -#define P3 a00, a23, a41, a14, a32, a24, a42, a10, a33, a01, a43, a11, \ - a34, a02, a20, a12, a30, a03, a21, a44, a31, a04, a22, a40, a13 -#define P4 a00, a12, a24, a31, a43, a42, a04, a11, a23, a30, a34, a41, \ - a03, a10, a22, a21, a33, a40, a02, a14, a13, a20, a32, a44, a01 -#define P5 a00, a21, a42, a13, a34, a04, a20, a41, a12, a33, a03, a24, \ - a40, a11, a32, a02, a23, a44, a10, a31, a01, a22, a43, a14, a30 -#define P6 a00, a02, a04, a01, a03, a20, a22, a24, a21, a23, a40, a42, \ - a44, a41, a43, a10, a12, a14, a11, a13, a30, a32, a34, a31, a33 -#define P7 a00, a10, a20, a30, a40, a22, a32, a42, a02, a12, a44, a04, \ - a14, a24, a34, a11, a21, a31, a41, a01, a33, a43, a03, a13, a23 -#define P8 a00, a11, a22, a33, a44, a32, a43, a04, a10, a21, a14, a20, \ - a31, a42, a03, a41, a02, a13, a24, a30, a23, a34, a40, a01, a12 -#define P9 a00, a41, a32, a23, a14, a43, a34, a20, a11, a02, a31, a22, \ - a13, a04, a40, a24, a10, a01, a42, a33, a12, a03, a44, a30, a21 -#define P10 a00, a24, a43, a12, a31, a34, a03, a22, a41, a10, a13, a32, \ - a01, a20, a44, a42, a11, a30, a04, a23, a21, a40, a14, a33, a02 -#define P11 a00, a42, a34, a21, a13, a03, a40, a32, a24, a11, a01, a43, \ - a30, a22, a14, a04, a41, a33, a20, a12, a02, a44, a31, a23, a10 -#define P12 a00, a04, a03, a02, a01, a40, a44, a43, a42, a41, a30, a34, \ - a33, a32, a31, a20, a24, a23, a22, a21, a10, a14, a13, a12, a11 -#define P13 a00, a20, a40, a10, a30, a44, a14, a34, a04, a24, a33, a03, \ - a23, a43, a13, a22, a42, a12, a32, a02, a11, a31, a01, a21, a41 -#define P14 a00, a22, a44, a11, a33, a14, a31, a03, a20, a42, a23, a40, \ - a12, a34, a01, a32, a04, a21, a43, a10, a41, a13, a30, a02, a24 -#define P15 a00, a32, a14, a41, a23, a31, a13, a40, a22, a04, a12, a44, \ - a21, a03, a30, a43, a20, a02, a34, a11, a24, a01, a33, a10, a42 -#define P16 a00, a43, a31, a24, a12, a13, a01, a44, a32, a20, a21, a14, \ - a02, a40, a33, a34, a22, a10, a03, a41, a42, a30, a23, a11, a04 -#define P17 a00, a34, a13, a42, a21, a01, a30, a14, a43, a22, a02, a31, \ - a10, a44, a23, a03, a32, a11, a40, a24, a04, a33, a12, a41, a20 -#define P18 a00, a03, a01, a04, a02, a30, a33, a31, a34, a32, a10, a13, \ - a11, a14, a12, a40, a43, a41, a44, a42, a20, a23, a21, a24, a22 -#define P19 a00, a40, a30, a20, a10, a33, a23, a13, a03, a43, a11, a01, \ - a41, a31, a21, a44, a34, a24, a14, a04, a22, a12, a02, a42, a32 -#define P20 a00, a44, a33, a22, a11, a23, a12, a01, a40, a34, a41, a30, \ - a24, a13, a02, a14, a03, a42, a31, a20, a32, a21, a10, a04, a43 -#define P21 a00, a14, a23, a32, a41, a12, a21, a30, a44, a03, a24, a33, \ - a42, a01, a10, a31, a40, a04, a13, a22, a43, a02, a11, a20, a34 -#define P22 a00, a31, a12, a43, a24, a21, a02, a33, a14, a40, a42, a23, \ - a04, a30, a11, a13, a44, a20, a01, a32, a34, a10, a41, a22, a03 -#define P23 a00, a13, a21, a34, a42, a02, a10, a23, a31, a44, a04, a12, \ - a20, a33, a41, a01, a14, a22, a30, a43, a03, a11, a24, a32, a40 - -#define P1_TO_P0 do { \ - DECL64(t); \ - MOV64(t, a01); \ - MOV64(a01, a30); \ - MOV64(a30, a33); \ - MOV64(a33, a23); \ - MOV64(a23, a12); \ - MOV64(a12, a21); \ - MOV64(a21, a02); \ - MOV64(a02, a10); \ - MOV64(a10, a11); \ - MOV64(a11, a41); \ - MOV64(a41, a24); \ - MOV64(a24, a42); \ - MOV64(a42, a04); \ - MOV64(a04, a20); \ - MOV64(a20, a22); \ - MOV64(a22, a32); \ - MOV64(a32, a43); \ - MOV64(a43, a34); \ - MOV64(a34, a03); \ - MOV64(a03, a40); \ - MOV64(a40, a44); \ - MOV64(a44, a14); \ - MOV64(a14, a31); \ - MOV64(a31, a13); \ - MOV64(a13, t); \ - } while (0) - -#define P2_TO_P0 do { \ - DECL64(t); \ - MOV64(t, a01); \ - MOV64(a01, a33); \ - MOV64(a33, a12); \ - MOV64(a12, a02); \ - MOV64(a02, a11); \ - MOV64(a11, a24); \ - MOV64(a24, a04); \ - MOV64(a04, a22); \ - MOV64(a22, a43); \ - MOV64(a43, a03); \ - MOV64(a03, a44); \ - MOV64(a44, a31); \ - MOV64(a31, t); \ - MOV64(t, a10); \ - MOV64(a10, a41); \ - MOV64(a41, a42); \ - MOV64(a42, a20); \ - MOV64(a20, a32); \ - MOV64(a32, a34); \ - MOV64(a34, a40); \ - MOV64(a40, a14); \ - MOV64(a14, a13); \ - MOV64(a13, a30); \ - MOV64(a30, a23); \ - MOV64(a23, a21); \ - MOV64(a21, t); \ - } while (0) - -#define P4_TO_P0 do { \ - DECL64(t); \ - MOV64(t, a01); \ - MOV64(a01, a12); \ - MOV64(a12, a11); \ - MOV64(a11, a04); \ - MOV64(a04, a43); \ - MOV64(a43, a44); \ - MOV64(a44, t); \ - MOV64(t, a02); \ - MOV64(a02, a24); \ - MOV64(a24, a22); \ - MOV64(a22, a03); \ - MOV64(a03, a31); \ - MOV64(a31, a33); \ - MOV64(a33, t); \ - MOV64(t, a10); \ - MOV64(a10, a42); \ - MOV64(a42, a32); \ - MOV64(a32, a40); \ - MOV64(a40, a13); \ - MOV64(a13, a23); \ - MOV64(a23, t); \ - MOV64(t, a14); \ - MOV64(a14, a30); \ - MOV64(a30, a21); \ - MOV64(a21, a41); \ - MOV64(a41, a20); \ - MOV64(a20, a34); \ - MOV64(a34, t); \ - } while (0) - -#define P6_TO_P0 do { \ - DECL64(t); \ - MOV64(t, a01); \ - MOV64(a01, a02); \ - MOV64(a02, a04); \ - MOV64(a04, a03); \ - MOV64(a03, t); \ - MOV64(t, a10); \ - MOV64(a10, a20); \ - MOV64(a20, a40); \ - MOV64(a40, a30); \ - MOV64(a30, t); \ - MOV64(t, a11); \ - MOV64(a11, a22); \ - MOV64(a22, a44); \ - MOV64(a44, a33); \ - MOV64(a33, t); \ - MOV64(t, a12); \ - MOV64(a12, a24); \ - MOV64(a24, a43); \ - MOV64(a43, a31); \ - MOV64(a31, t); \ - MOV64(t, a13); \ - MOV64(a13, a21); \ - MOV64(a21, a42); \ - MOV64(a42, a34); \ - MOV64(a34, t); \ - MOV64(t, a14); \ - MOV64(a14, a23); \ - MOV64(a23, a41); \ - MOV64(a41, a32); \ - MOV64(a32, t); \ - } while (0) - -#define P8_TO_P0 do { \ - DECL64(t); \ - MOV64(t, a01); \ - MOV64(a01, a11); \ - MOV64(a11, a43); \ - MOV64(a43, t); \ - MOV64(t, a02); \ - MOV64(a02, a22); \ - MOV64(a22, a31); \ - MOV64(a31, t); \ - MOV64(t, a03); \ - MOV64(a03, a33); \ - MOV64(a33, a24); \ - MOV64(a24, t); \ - MOV64(t, a04); \ - MOV64(a04, a44); \ - MOV64(a44, a12); \ - MOV64(a12, t); \ - MOV64(t, a10); \ - MOV64(a10, a32); \ - MOV64(a32, a13); \ - MOV64(a13, t); \ - MOV64(t, a14); \ - MOV64(a14, a21); \ - MOV64(a21, a20); \ - MOV64(a20, t); \ - MOV64(t, a23); \ - MOV64(a23, a42); \ - MOV64(a42, a40); \ - MOV64(a40, t); \ - MOV64(t, a30); \ - MOV64(a30, a41); \ - MOV64(a41, a34); \ - MOV64(a34, t); \ - } while (0) - -#define P12_TO_P0 do { \ - DECL64(t); \ - MOV64(t, a01); \ - MOV64(a01, a04); \ - MOV64(a04, t); \ - MOV64(t, a02); \ - MOV64(a02, a03); \ - MOV64(a03, t); \ - MOV64(t, a10); \ - MOV64(a10, a40); \ - MOV64(a40, t); \ - MOV64(t, a11); \ - MOV64(a11, a44); \ - MOV64(a44, t); \ - MOV64(t, a12); \ - MOV64(a12, a43); \ - MOV64(a43, t); \ - MOV64(t, a13); \ - MOV64(a13, a42); \ - MOV64(a42, t); \ - MOV64(t, a14); \ - MOV64(a14, a41); \ - MOV64(a41, t); \ - MOV64(t, a20); \ - MOV64(a20, a30); \ - MOV64(a30, t); \ - MOV64(t, a21); \ - MOV64(a21, a34); \ - MOV64(a34, t); \ - MOV64(t, a22); \ - MOV64(a22, a33); \ - MOV64(a33, t); \ - MOV64(t, a23); \ - MOV64(a23, a32); \ - MOV64(a32, t); \ - MOV64(t, a24); \ - MOV64(a24, a31); \ - MOV64(a31, t); \ - } while (0) - -#define LPAR ( -#define RPAR ) - -#define KF_ELT(r, s, k) do { \ - THETA LPAR P ## r RPAR; \ - RHO LPAR P ## r RPAR; \ - KHI LPAR P ## s RPAR; \ - IOTA(k); \ - } while (0) - -#define DO(x) x - -#define KECCAK_F_1600 DO(KECCAK_F_1600_) - -#if SPH_KECCAK_UNROLL == 1 - -#define KECCAK_F_1600_ do { \ - int j; \ - for (j = 0; j < 24; j ++) { \ - KF_ELT( 0, 1, RC[j + 0]); \ - P1_TO_P0; \ - } \ - } while (0) - -#elif SPH_KECCAK_UNROLL == 2 - -#define KECCAK_F_1600_ do { \ - int j; \ - for (j = 0; j < 24; j += 2) { \ - KF_ELT( 0, 1, RC[j + 0]); \ - KF_ELT( 1, 2, RC[j + 1]); \ - P2_TO_P0; \ - } \ - } while (0) - -#elif SPH_KECCAK_UNROLL == 4 - -#define KECCAK_F_1600_ do { \ - int j; \ - for (j = 0; j < 24; j += 4) { \ - KF_ELT( 0, 1, RC[j + 0]); \ - KF_ELT( 1, 2, RC[j + 1]); \ - KF_ELT( 2, 3, RC[j + 2]); \ - KF_ELT( 3, 4, RC[j + 3]); \ - P4_TO_P0; \ - } \ - } while (0) - -#elif SPH_KECCAK_UNROLL == 6 - -#define KECCAK_F_1600_ do { \ - int j; \ - for (j = 0; j < 24; j += 6) { \ - KF_ELT( 0, 1, RC[j + 0]); \ - KF_ELT( 1, 2, RC[j + 1]); \ - KF_ELT( 2, 3, RC[j + 2]); \ - KF_ELT( 3, 4, RC[j + 3]); \ - KF_ELT( 4, 5, RC[j + 4]); \ - KF_ELT( 5, 6, RC[j + 5]); \ - P6_TO_P0; \ - } \ - } while (0) - -#elif SPH_KECCAK_UNROLL == 8 - -#define KECCAK_F_1600_ do { \ - int j; \ - for (j = 0; j < 24; j += 8) { \ - KF_ELT( 0, 1, RC[j + 0]); \ - KF_ELT( 1, 2, RC[j + 1]); \ - KF_ELT( 2, 3, RC[j + 2]); \ - KF_ELT( 3, 4, RC[j + 3]); \ - KF_ELT( 4, 5, RC[j + 4]); \ - KF_ELT( 5, 6, RC[j + 5]); \ - KF_ELT( 6, 7, RC[j + 6]); \ - KF_ELT( 7, 8, RC[j + 7]); \ - P8_TO_P0; \ - } \ - } while (0) - -#elif SPH_KECCAK_UNROLL == 12 - -#define KECCAK_F_1600_ do { \ - int j; \ - for (j = 0; j < 24; j += 12) { \ - KF_ELT( 0, 1, RC[j + 0]); \ - KF_ELT( 1, 2, RC[j + 1]); \ - KF_ELT( 2, 3, RC[j + 2]); \ - KF_ELT( 3, 4, RC[j + 3]); \ - KF_ELT( 4, 5, RC[j + 4]); \ - KF_ELT( 5, 6, RC[j + 5]); \ - KF_ELT( 6, 7, RC[j + 6]); \ - KF_ELT( 7, 8, RC[j + 7]); \ - KF_ELT( 8, 9, RC[j + 8]); \ - KF_ELT( 9, 10, RC[j + 9]); \ - KF_ELT(10, 11, RC[j + 10]); \ - KF_ELT(11, 12, RC[j + 11]); \ - P12_TO_P0; \ - } \ - } while (0) - -#elif SPH_KECCAK_UNROLL == 0 - -#define KECCAK_F_1600_ do { \ - KF_ELT( 0, 1, RC[ 0]); \ - KF_ELT( 1, 2, RC[ 1]); \ - KF_ELT( 2, 3, RC[ 2]); \ - KF_ELT( 3, 4, RC[ 3]); \ - KF_ELT( 4, 5, RC[ 4]); \ - KF_ELT( 5, 6, RC[ 5]); \ - KF_ELT( 6, 7, RC[ 6]); \ - KF_ELT( 7, 8, RC[ 7]); \ - KF_ELT( 8, 9, RC[ 8]); \ - KF_ELT( 9, 10, RC[ 9]); \ - KF_ELT(10, 11, RC[10]); \ - KF_ELT(11, 12, RC[11]); \ - KF_ELT(12, 13, RC[12]); \ - KF_ELT(13, 14, RC[13]); \ - KF_ELT(14, 15, RC[14]); \ - KF_ELT(15, 16, RC[15]); \ - KF_ELT(16, 17, RC[16]); \ - KF_ELT(17, 18, RC[17]); \ - KF_ELT(18, 19, RC[18]); \ - KF_ELT(19, 20, RC[19]); \ - KF_ELT(20, 21, RC[20]); \ - KF_ELT(21, 22, RC[21]); \ - KF_ELT(22, 23, RC[22]); \ - KF_ELT(23, 0, RC[23]); \ - } while (0) - -#else - -#error Unimplemented unroll count for Keccak. - -#endif - -static void -keccak_init(sph_keccak_context *kc, unsigned out_size) -{ - int i; - -#if SPH_KECCAK_64 - for (i = 0; i < 25; i ++) - kc->u.wide[i] = 0; - /* - * Initialization for the "lane complement". - */ - kc->u.wide[ 1] = SPH_C64(0xFFFFFFFFFFFFFFFF); - kc->u.wide[ 2] = SPH_C64(0xFFFFFFFFFFFFFFFF); - kc->u.wide[ 8] = SPH_C64(0xFFFFFFFFFFFFFFFF); - kc->u.wide[12] = SPH_C64(0xFFFFFFFFFFFFFFFF); - kc->u.wide[17] = SPH_C64(0xFFFFFFFFFFFFFFFF); - kc->u.wide[20] = SPH_C64(0xFFFFFFFFFFFFFFFF); -#else - - for (i = 0; i < 50; i ++) - kc->u.narrow[i] = 0; - /* - * Initialization for the "lane complement". - * Note: since we set to all-one full 64-bit words, - * interleaving (if applicable) is a no-op. - */ - kc->u.narrow[ 2] = SPH_C32(0xFFFFFFFF); - kc->u.narrow[ 3] = SPH_C32(0xFFFFFFFF); - kc->u.narrow[ 4] = SPH_C32(0xFFFFFFFF); - kc->u.narrow[ 5] = SPH_C32(0xFFFFFFFF); - kc->u.narrow[16] = SPH_C32(0xFFFFFFFF); - kc->u.narrow[17] = SPH_C32(0xFFFFFFFF); - kc->u.narrow[24] = SPH_C32(0xFFFFFFFF); - kc->u.narrow[25] = SPH_C32(0xFFFFFFFF); - kc->u.narrow[34] = SPH_C32(0xFFFFFFFF); - kc->u.narrow[35] = SPH_C32(0xFFFFFFFF); - kc->u.narrow[40] = SPH_C32(0xFFFFFFFF); - kc->u.narrow[41] = SPH_C32(0xFFFFFFFF); -#endif - kc->ptr = 0; - kc->lim = 200 - (out_size >> 2); -} - -static void -keccak_core(sph_keccak_context *kc, const void *data, size_t len, size_t lim) -{ - unsigned char *buf; - size_t ptr; - DECL_STATE - - buf = kc->buf; - ptr = kc->ptr; - - if (len < (lim - ptr)) { - memcpy(buf + ptr, data, len); - kc->ptr = ptr + len; - return; - } - - READ_STATE(kc); - while (len > 0) { - size_t clen; - - clen = (lim - ptr); - if (clen > len) - clen = len; - memcpy(buf + ptr, data, clen); - ptr += clen; - data = (const unsigned char *)data + clen; - len -= clen; - if (ptr == lim) { - INPUT_BUF(lim); - KECCAK_F_1600; - ptr = 0; - } - } - WRITE_STATE(kc); - kc->ptr = ptr; -} - -#if SPH_KECCAK_64 - -#define DEFCLOSE(d, lim) \ - static void keccak_close ## d( \ - sph_keccak_context *kc, unsigned ub, unsigned n, void *dst) \ - { \ - unsigned eb; \ - union { \ - unsigned char tmp[lim + 1]; \ - sph_u64 dummy; /* for alignment */ \ - } u; \ - size_t j; \ - \ - eb = (0x100 | (ub & 0xFF)) >> (8 - n); \ - if (kc->ptr == (lim - 1)) { \ - if (n == 7) { \ - u.tmp[0] = eb; \ - memset(u.tmp + 1, 0, lim - 1); \ - u.tmp[lim] = 0x80; \ - j = 1 + lim; \ - } else { \ - u.tmp[0] = eb | 0x80; \ - j = 1; \ - } \ - } else { \ - j = lim - kc->ptr; \ - u.tmp[0] = eb; \ - memset(u.tmp + 1, 0, j - 2); \ - u.tmp[j - 1] = 0x80; \ - } \ - keccak_core(kc, u.tmp, j, lim); \ - /* Finalize the "lane complement" */ \ - kc->u.wide[ 1] = ~kc->u.wide[ 1]; \ - kc->u.wide[ 2] = ~kc->u.wide[ 2]; \ - kc->u.wide[ 8] = ~kc->u.wide[ 8]; \ - kc->u.wide[12] = ~kc->u.wide[12]; \ - kc->u.wide[17] = ~kc->u.wide[17]; \ - kc->u.wide[20] = ~kc->u.wide[20]; \ - for (j = 0; j < d; j += 8) \ - sph_enc64le_aligned(u.tmp + j, kc->u.wide[j >> 3]); \ - memcpy(dst, u.tmp, d); \ - keccak_init(kc, (unsigned)d << 3); \ - } \ - -#else - -#define DEFCLOSE(d, lim) \ - static void keccak_close ## d( \ - sph_keccak_context *kc, unsigned ub, unsigned n, void *dst) \ - { \ - unsigned eb; \ - union { \ - unsigned char tmp[lim + 1]; \ - sph_u64 dummy; /* for alignment */ \ - } u; \ - size_t j; \ - \ - eb = (0x100 | (ub & 0xFF)) >> (8 - n); \ - if (kc->ptr == (lim - 1)) { \ - if (n == 7) { \ - u.tmp[0] = eb; \ - memset(u.tmp + 1, 0, lim - 1); \ - u.tmp[lim] = 0x80; \ - j = 1 + lim; \ - } else { \ - u.tmp[0] = eb | 0x80; \ - j = 1; \ - } \ - } else { \ - j = lim - kc->ptr; \ - u.tmp[0] = eb; \ - memset(u.tmp + 1, 0, j - 2); \ - u.tmp[j - 1] = 0x80; \ - } \ - keccak_core(kc, u.tmp, j, lim); \ - /* Finalize the "lane complement" */ \ - kc->u.narrow[ 2] = ~kc->u.narrow[ 2]; \ - kc->u.narrow[ 3] = ~kc->u.narrow[ 3]; \ - kc->u.narrow[ 4] = ~kc->u.narrow[ 4]; \ - kc->u.narrow[ 5] = ~kc->u.narrow[ 5]; \ - kc->u.narrow[16] = ~kc->u.narrow[16]; \ - kc->u.narrow[17] = ~kc->u.narrow[17]; \ - kc->u.narrow[24] = ~kc->u.narrow[24]; \ - kc->u.narrow[25] = ~kc->u.narrow[25]; \ - kc->u.narrow[34] = ~kc->u.narrow[34]; \ - kc->u.narrow[35] = ~kc->u.narrow[35]; \ - kc->u.narrow[40] = ~kc->u.narrow[40]; \ - kc->u.narrow[41] = ~kc->u.narrow[41]; \ - /* un-interleave */ \ - for (j = 0; j < 50; j += 2) \ - UNINTERLEAVE(kc->u.narrow[j], kc->u.narrow[j + 1]); \ - for (j = 0; j < d; j += 4) \ - sph_enc32le_aligned(u.tmp + j, kc->u.narrow[j >> 2]); \ - memcpy(dst, u.tmp, d); \ - keccak_init(kc, (unsigned)d << 3); \ - } \ - -#endif - -DEFCLOSE(28, 144) -DEFCLOSE(32, 136) -DEFCLOSE(48, 104) -DEFCLOSE(64, 72) - -/* see sph_keccak.h */ -void -sph_keccak224_init(void *cc) -{ - keccak_init(cc, 224); -} - -/* see sph_keccak.h */ -void -sph_keccak224(void *cc, const void *data, size_t len) -{ - keccak_core(cc, data, len, 144); -} - -/* see sph_keccak.h */ -void -sph_keccak224_close(void *cc, void *dst) -{ - sph_keccak224_addbits_and_close(cc, 0, 0, dst); -} - -/* see sph_keccak.h */ -void -sph_keccak224_addbits_and_close(void *cc, unsigned ub, unsigned n, void *dst) -{ - keccak_close28(cc, ub, n, dst); -} - -/* see sph_keccak.h */ -void -sph_keccak256_init(void *cc) -{ - keccak_init(cc, 256); -} - -/* see sph_keccak.h */ -void -sph_keccak256(void *cc, const void *data, size_t len) -{ - keccak_core(cc, data, len, 136); -} - -/* see sph_keccak.h */ -void -sph_keccak256_close(void *cc, void *dst) -{ - sph_keccak256_addbits_and_close(cc, 0, 0, dst); -} - -/* see sph_keccak.h */ -void -sph_keccak256_addbits_and_close(void *cc, unsigned ub, unsigned n, void *dst) -{ - keccak_close32(cc, ub, n, dst); -} - -/* see sph_keccak.h */ -void -sph_keccak384_init(void *cc) -{ - keccak_init(cc, 384); -} - -/* see sph_keccak.h */ -void -sph_keccak384(void *cc, const void *data, size_t len) -{ - keccak_core(cc, data, len, 104); -} - -/* see sph_keccak.h */ -void -sph_keccak384_close(void *cc, void *dst) -{ - sph_keccak384_addbits_and_close(cc, 0, 0, dst); -} - -/* see sph_keccak.h */ -void -sph_keccak384_addbits_and_close(void *cc, unsigned ub, unsigned n, void *dst) -{ - keccak_close48(cc, ub, n, dst); -} - -/* see sph_keccak.h */ -void -sph_keccak512_init(void *cc) -{ - keccak_init(cc, 512); -} - -/* see sph_keccak.h */ -void -sph_keccak512(void *cc, const void *data, size_t len) -{ - keccak_core(cc, data, len, 72); -} - -/* see sph_keccak.h */ -void -sph_keccak512_close(void *cc, void *dst) -{ - sph_keccak512_addbits_and_close(cc, 0, 0, dst); -} - -/* see sph_keccak.h */ -void -sph_keccak512_addbits_and_close(void *cc, unsigned ub, unsigned n, void *dst) -{ - keccak_close64(cc, ub, n, dst); -} - - -#ifdef __cplusplus -} -#endif From 7350b1b7fa6626ea4e508ffd7f47a94b1c90c760 Mon Sep 17 00:00:00 2001 From: CryptoCentric Date: Thu, 25 Apr 2019 10:26:15 +0100 Subject: [PATCH 004/282] Add tests for special rules for slow blocks on povnet/testnet * Add tests for special rules for slow blocks on devnet/testnet * add 20m and 3h --- src/test/pow_tests.cpp | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/src/test/pow_tests.cpp b/src/test/pow_tests.cpp index 041d5f460790..46c040d953e8 100644 --- a/src/test/pow_tests.cpp +++ b/src/test/pow_tests.cpp @@ -120,6 +120,26 @@ BOOST_AUTO_TEST_CASE(get_next_work) CBlockHeader blockHeader; blockHeader.nTime = 1408732505; // Block #123457 BOOST_CHECK_EQUAL(GetNextWorkRequired(&blockIndexLast, &blockHeader, params), 0x1b1441de); // Block #123457 has 0x1b1441de + + // test special rules for slow blocks on povnet/testnet + SoftSetBoolArg("-povnet", true); + SelectParams(CBaseChainParams::POVNET); + const Consensus::Params& paramspov = Params().GetConsensus(); + + // make sure normal rules apply + blockHeader.nTime = 1408732505; // Block #123457 + BOOST_CHECK_EQUAL(GetNextWorkRequired(&blockIndexLast, &blockHeader, paramspov), 0x1b1441de); // Block #123457 has 0x1b1441de + + // 10x higher target + blockHeader.nTime = 1408733090; // Block #123457 (10m+1sec) + BOOST_CHECK_EQUAL(GetNextWorkRequired(&blockIndexLast, &blockHeader, paramspov), 0x1c00c8f8); // Block #123457 has 0x1c00c8f8 + blockHeader.nTime = 1408733689; // Block #123457 (20m) + BOOST_CHECK_EQUAL(GetNextWorkRequired(&blockIndexLast, &blockHeader, paramspov), 0x1c00c8f8); // Block #123457 has 0x1c00c8f8 + // lowest diff possible + blockHeader.nTime = 1408739690; // Block #123457 (2h+1sec) + BOOST_CHECK_EQUAL(GetNextWorkRequired(&blockIndexLast, &blockHeader, paramspov), 0x207fffff); // Block #123457 has 0x207fffff + blockHeader.nTime = 1408743289; // Block #123457 (3h) + BOOST_CHECK_EQUAL(GetNextWorkRequired(&blockIndexLast, &blockHeader, paramspov), 0x207fffff); // Block #123457 has 0x207fffff } /* Test the constraint on the upper bound for next work */ From 76c557b03e7da744dcd0bbf327aa923eb5dbfc2a Mon Sep 17 00:00:00 2001 From: gladcow Date: Thu, 12 Jul 2018 12:01:48 +0300 Subject: [PATCH 005/282] Save/load InstantSend cache (#2051) * CTxLockCandidate serialization * COutPointLock serialization * CInstantSend serialization * Read/write instantsend.dat file * Read\write InstantSend cache only if InstantSend is enabled --- src/init.cpp | 15 ++++++++++++ src/instantx.cpp | 18 +++++++++++++- src/instantx.h | 62 ++++++++++++++++++++++++++++++++++++++++++++++-- 3 files changed, 92 insertions(+), 3 deletions(-) diff --git a/src/init.cpp b/src/init.cpp index aac5d4d606db..0a71e69d292c 100644 --- a/src/init.cpp +++ b/src/init.cpp @@ -251,6 +251,11 @@ void PrepareShutdown() flatdb3.Dump(governance); CFlatDB flatdb4("netfulfilled.dat", "magicFulfilledCache"); flatdb4.Dump(netfulfilledman); + if(fEnableInstantSend) + { + CFlatDB flatdb5("instantsend.dat", "magicInstantSendCache"); + flatdb5.Dump(instantsend); + } } UnregisterNodeSignals(GetNodeSignals()); @@ -1906,6 +1911,16 @@ bool AppInitMain(boost::thread_group& threadGroup, CScheduler& scheduler) if(!flatdb4.Load(netfulfilledman)) { return InitError(_("Failed to load fulfilled requests cache from") + "\n" + (pathDB / strDBName).string()); } + + if(fEnableInstantSend) + { + strDBName = "instantsend.dat"; + uiInterface.InitMessage(_("Loading InstantSend data cache...")); + CFlatDB flatdb5(strDBName, "magicInstantSendCache"); + if(!flatdb5.Load(instantsend)) { + return InitError(_("Failed to load InstantSend data cache from") + "\n" + (pathDB / strDBName).string()); + } + } } diff --git a/src/instantx.cpp b/src/instantx.cpp index 26ff7017771e..1351e01ce607 100644 --- a/src/instantx.cpp +++ b/src/instantx.cpp @@ -38,6 +38,7 @@ int nInstantSendDepth = DEFAULT_INSTANTSEND_DEPTH; int nCompleteTXLocks; CInstantSend instantsend; +const std::string CInstantSend::SERIALIZATION_VERSION_STRING = "CInstantSend-Version-1"; // Transaction Locks // @@ -798,6 +799,21 @@ bool CInstantSend::IsInstantSendReadyToLock(const uint256& txHash) return it != mapTxLockCandidates.end() && it->second.IsAllOutPointsReady(); } +void CInstantSend::Clear() +{ + LOCK(cs_instantsend); + + mapLockRequestAccepted.clear(); + mapLockRequestRejected.clear(); + mapTxLockVotes.clear(); + mapTxLockVotesOrphan.clear(); + mapTxLockCandidates.clear(); + mapVotedOutpoints.clear(); + mapLockedOutpoints.clear(); + mapMasternodeOrphanVotes.clear(); + nCachedBlockHeight = 0; +} + bool CInstantSend::IsLockedInstantSendTransaction(const uint256& txHash) { if(!fEnableInstantSend || GetfLargeWorkForkFound() || GetfLargeWorkInvalidChainFound() || @@ -929,7 +945,7 @@ void CInstantSend::SyncTransaction(const CTransaction& tx, const CBlockIndex *pi } } -std::string CInstantSend::ToString() +std::string CInstantSend::ToString() const { LOCK(cs_instantsend); return strprintf("Lock Candidates: %llu, Votes %llu", mapTxLockCandidates.size(), mapTxLockVotes.size()); diff --git a/src/instantx.h b/src/instantx.h index 694c957690c8..b4885361c595 100644 --- a/src/instantx.h +++ b/src/instantx.h @@ -54,6 +54,8 @@ extern int nCompleteTXLocks; class CInstantSend { private: + static const std::string SERIALIZATION_VERSION_STRING; + // Keep track of current block height int nCachedBlockHeight; @@ -92,7 +94,37 @@ class CInstantSend bool IsInstantSendReadyToLock(const uint256 &txHash); public: - CCriticalSection cs_instantsend; + mutable CCriticalSection cs_instantsend; + + ADD_SERIALIZE_METHODS; + + template + inline void SerializationOp(Stream& s, Operation ser_action) { + std::string strVersion; + if(ser_action.ForRead()) { + READWRITE(strVersion); + } + else { + strVersion = SERIALIZATION_VERSION_STRING; + READWRITE(strVersion); + } + + READWRITE(mapLockRequestAccepted); + READWRITE(mapLockRequestRejected); + READWRITE(mapTxLockVotes); + READWRITE(mapTxLockVotesOrphan); + READWRITE(mapTxLockCandidates); + READWRITE(mapVotedOutpoints); + READWRITE(mapLockedOutpoints); + READWRITE(mapMasternodeOrphanVotes); + READWRITE(nCachedBlockHeight); + + if(ser_action.ForRead() && (strVersion != SERIALIZATION_VERSION_STRING)) { + Clear(); + } + } + + void Clear(); void ProcessMessage(CNode* pfrom, const std::string& strCommand, CDataStream& vRecv, CConnman& connman); @@ -127,7 +159,7 @@ class CInstantSend void UpdatedBlockTip(const CBlockIndex *pindex); void SyncTransaction(const CTransaction& tx, const CBlockIndex *pindex, int posInBlock); - std::string ToString(); + std::string ToString() const; }; /** @@ -265,6 +297,8 @@ class COutPointLock static const int SIGNATURES_REQUIRED = 6; static const int SIGNATURES_TOTAL = 10; + COutPointLock() {} + COutPointLock(const COutPoint& outpointIn) : outpoint(outpointIn), mapMasternodeVotes() @@ -272,6 +306,15 @@ class COutPointLock COutPoint GetOutpoint() const { return outpoint; } + ADD_SERIALIZE_METHODS; + + template + inline void SerializationOp(Stream& s, Operation ser_action) { + READWRITE(outpoint); + READWRITE(mapMasternodeVotes); + READWRITE(fAttacked); + } + bool AddVote(const CTxLockVote& vote); std::vector GetVotes() const; bool HasMasternodeVoted(const COutPoint& outpointMasternodeIn) const; @@ -292,6 +335,11 @@ class CTxLockCandidate int64_t nTimeCreated; public: + CTxLockCandidate() : + nConfirmedHeight(-1), + nTimeCreated(GetTime()) + {} + CTxLockCandidate(const CTxLockRequest& txLockRequestIn) : nConfirmedHeight(-1), nTimeCreated(GetTime()), @@ -302,6 +350,16 @@ class CTxLockCandidate CTxLockRequest txLockRequest; std::map mapOutPointLocks; + ADD_SERIALIZE_METHODS; + + template + inline void SerializationOp(Stream& s, Operation ser_action) { + READWRITE(txLockRequest); + READWRITE(mapOutPointLocks); + READWRITE(nTimeCreated); + READWRITE(nConfirmedHeight); + } + uint256 GetHash() const { return txLockRequest.GetHash(); } void AddOutPointLock(const COutPoint& outpoint); From 243e7ca74c3315405a8978904e212b24125e53ec Mon Sep 17 00:00:00 2001 From: PaulieD Date: Thu, 12 Jul 2018 04:02:51 -0500 Subject: [PATCH 006/282] PrivateSend Enhancement: Up default round count to 4 and allow user to mix up to 16 rounds (#2128) * Allows a user to mix up to 16 rounds All codebase appears to accept up to 16 rounds, however this form was capped at 8; restricting users to 2-8 rounds. This commit allows a user to actually use up to 16 rounds in practice. This will greatly enhance the privacy of those very worried about their privacy, as well as possibly increasing liquidity and increasing the privacy of all users. * Up the default for PS mixing to 4 rounds. --- src/privatesend-client.h | 2 +- src/qt/forms/optionsdialog.ui | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/privatesend-client.h b/src/privatesend-client.h index 170b19153d6f..9e6dac2d6bef 100644 --- a/src/privatesend-client.h +++ b/src/privatesend-client.h @@ -22,7 +22,7 @@ static const int MIN_PRIVATESEND_LIQUIDITY = 0; static const int MAX_PRIVATESEND_ROUNDS = 16; static const int MAX_PRIVATESEND_AMOUNT = MAX_MONEY / COIN; static const int MAX_PRIVATESEND_LIQUIDITY = 100; -static const int DEFAULT_PRIVATESEND_ROUNDS = 2; +static const int DEFAULT_PRIVATESEND_ROUNDS = 4; static const int DEFAULT_PRIVATESEND_AMOUNT = 1000; static const int DEFAULT_PRIVATESEND_LIQUIDITY = 0; diff --git a/src/qt/forms/optionsdialog.ui b/src/qt/forms/optionsdialog.ui index 562d015794a1..72ec5992a7ef 100644 --- a/src/qt/forms/optionsdialog.ui +++ b/src/qt/forms/optionsdialog.ui @@ -229,7 +229,7 @@ 2 - 8 + 16 4 From 8432b99834e61bd95e2ad29dccb709f75ae6c5c1 Mon Sep 17 00:00:00 2001 From: UdjinM6 Date: Thu, 12 Jul 2018 12:03:26 +0300 Subject: [PATCH 007/282] Remove obsolete Dark Coin functionality --- contrib/absolute-qt.pro | 1 - src/Makefile.qt.include | 4 ---- src/qt/darksendconfig.h | 37 ------------------------------------- src/qt/overviewpage.cpp | 10 ---------- 4 files changed, 52 deletions(-) delete mode 100644 src/qt/darksendconfig.h diff --git a/contrib/absolute-qt.pro b/contrib/absolute-qt.pro index 9d0e6788c1d4..12a489f9f516 100644 --- a/contrib/absolute-qt.pro +++ b/contrib/absolute-qt.pro @@ -3,7 +3,6 @@ FORMS += \ ../src/qt/forms/addressbookpage.ui \ ../src/qt/forms/askpassphrasedialog.ui \ ../src/qt/forms/coincontroldialog.ui \ - ../src/qt/forms/darksendconfig.ui \ ../src/qt/forms/debugwindow.ui \ ../src/qt/forms/editaddressdialog.ui \ ../src/qt/forms/helpmessagedialog.ui \ diff --git a/src/Makefile.qt.include b/src/Makefile.qt.include index c2ae6711751f..1a6657d42d2d 100644 --- a/src/Makefile.qt.include +++ b/src/Makefile.qt.include @@ -29,7 +29,6 @@ QT_FORMS_UI = \ qt/forms/addressbookpage.ui \ qt/forms/askpassphrasedialog.ui \ qt/forms/coincontroldialog.ui \ - qt/forms/darksendconfig.ui \ qt/forms/editaddressdialog.ui \ qt/forms/helpmessagedialog.ui \ qt/forms/intro.ui \ @@ -60,7 +59,6 @@ QT_MOC_CPP = \ qt/moc_coincontroldialog.cpp \ qt/moc_coincontroltreewidget.cpp \ qt/moc_csvmodelwriter.cpp \ - qt/moc_darksendconfig.cpp \ qt/moc_editaddressdialog.cpp \ qt/moc_guiutil.cpp \ qt/moc_intro.cpp \ @@ -130,7 +128,6 @@ BITCOIN_QT_H = \ qt/coincontroldialog.h \ qt/coincontroltreewidget.h \ qt/csvmodelwriter.h \ - qt/darksendconfig.h \ qt/editaddressdialog.h \ qt/guiconstants.h \ qt/guiutil.h \ @@ -272,7 +269,6 @@ BITCOIN_QT_WALLET_CPP = \ qt/askpassphrasedialog.cpp \ qt/coincontroldialog.cpp \ qt/coincontroltreewidget.cpp \ - qt/darksendconfig.cpp \ qt/editaddressdialog.cpp \ qt/masternodelist.cpp \ qt/openuridialog.cpp \ diff --git a/src/qt/darksendconfig.h b/src/qt/darksendconfig.h deleted file mode 100644 index a1e1a37c5ef6..000000000000 --- a/src/qt/darksendconfig.h +++ /dev/null @@ -1,37 +0,0 @@ -#ifndef DARKSENDCONFIG_H -#define DARKSENDCONFIG_H - -#include - -namespace Ui { - class DarksendConfig; -} -class WalletModel; - -/** Multifunctional dialog to ask for passphrases. Used for encryption, unlocking, and changing the passphrase. - */ -class DarksendConfig : public QDialog -{ - Q_OBJECT - -public: - - DarksendConfig(QWidget *parent = 0); - ~DarksendConfig(); - - void setModel(WalletModel *model); - - -private: - Ui::DarksendConfig *ui; - WalletModel *model; - void configure(bool enabled, int coins, int rounds); - -private Q_SLOTS: - - void clickBasic(); - void clickHigh(); - void clickMax(); -}; - -#endif // DARKSENDCONFIG_H diff --git a/src/qt/overviewpage.cpp b/src/qt/overviewpage.cpp index 88d3e27c9fca..a2cf6225ac32 100644 --- a/src/qt/overviewpage.cpp +++ b/src/qt/overviewpage.cpp @@ -20,7 +20,6 @@ #include "walletmodel.h" #include "instantx.h" -#include "darksendconfig.h" #include "masternode-sync.h" #include "privatesend-client.h" @@ -647,15 +646,6 @@ void OverviewPage::togglePrivateSend(){ privateSendClient.UnlockCoins(); } else { ui->togglePrivateSend->setText(tr("Stop Mixing")); - - /* show darksend configuration if client has defaults set */ - - if(privateSendClient.nPrivateSendAmount == 0){ - DarksendConfig dlg(this); - dlg.setModel(walletModel); - dlg.exec(); - } - } } From 10387bcdafeb69d7815000c3691c0b34d4353319 Mon Sep 17 00:00:00 2001 From: gladcow Date: Thu, 12 Jul 2018 12:04:42 +0300 Subject: [PATCH 008/282] InstantSend Integration test * adjust `AddLocal` method only in regtest mode * Create Masternodes in regtest * sentinelping call for masternodes * set externalip option for masternodes in regtest * fix MNB relay during masternodes creation * fix node_count naming * instantsend doublespend * decrease node restarts * prevent spending masternode collaterals * move long test to the test list start * remove InstantSend spork sending * remove spork-specific code * fix checking double spend rejection --- qa/pull-tester/rpc-tests.py | 1 + qa/rpc-tests/p2p-instantsend.py | 192 ++++++++++++++++++++++++++++ qa/rpc-tests/test_framework/util.py | 2 +- src/chainparams.cpp | 13 +- src/chainparams.h | 3 + src/masternodeman.cpp | 4 +- src/net.cpp | 2 +- 7 files changed, 209 insertions(+), 8 deletions(-) create mode 100644 qa/rpc-tests/p2p-instantsend.py diff --git a/qa/pull-tester/rpc-tests.py b/qa/pull-tester/rpc-tests.py index 6a8997375dc0..948f3b034a14 100755 --- a/qa/pull-tester/rpc-tests.py +++ b/qa/pull-tester/rpc-tests.py @@ -117,6 +117,7 @@ 'fundrawtransaction.py', 'fundrawtransaction-hd.py', # vv Tests less than 2m vv + 'p2p-instantsend.py', 'wallet.py', 'wallet-accounts.py', 'wallet-dump.py', diff --git a/qa/rpc-tests/p2p-instantsend.py b/qa/rpc-tests/p2p-instantsend.py new file mode 100644 index 000000000000..33aaa755b6b0 --- /dev/null +++ b/qa/rpc-tests/p2p-instantsend.py @@ -0,0 +1,192 @@ +#!/usr/bin/env python3 +# Copyright (c) 2018 The Dash Core developers +# Distributed under the MIT software license, see the accompanying +# file COPYING or http://www.opensource.org/licenses/mit-license.php. + +from test_framework.mininode import * +from test_framework.test_framework import BitcoinTestFramework +from test_framework.util import * +from time import * + +''' +InstantSendTest -- test InstantSend functionality (prevent doublespend for unconfirmed transactions) +''' + +MASTERNODE_COLLATERAL = 1000 + + +class MasternodeInfo: + def __init__(self, key, collateral_id, collateral_out): + self.key = key + self.collateral_id = collateral_id + self.collateral_out = collateral_out + + +class InstantSendTest(BitcoinTestFramework): + def __init__(self): + super().__init__() + self.mn_count = 10 + self.num_nodes = self.mn_count + 4 + self.mninfo = [] + self.setup_clean_chain = True + self.is_network_split = False + # set sender, receiver, isolated nodes + self.isolated_idx = self.num_nodes - 1 + self.receiver_idx = self.num_nodes - 2 + self.sender_idx = self.num_nodes - 3 + + def create_simple_node(self): + idx = len(self.nodes) + self.nodes.append(start_node(idx, self.options.tmpdir, + ["-debug"])) + for i in range(0, idx): + connect_nodes(self.nodes[i], idx) + + def get_mnconf_file(self): + return os.path.join(self.options.tmpdir, "node0/regtest/masternode.conf") + + def prepare_masternodes(self): + for idx in range(0, self.mn_count): + key = self.nodes[0].masternode("genkey") + address = self.nodes[0].getnewaddress() + txid = self.nodes[0].sendtoaddress(address, MASTERNODE_COLLATERAL) + txrow = self.nodes[0].getrawtransaction(txid, True) + collateral_vout = 0 + for vout_idx in range(0, len(txrow["vout"])): + vout = txrow["vout"][vout_idx] + if vout["value"] == MASTERNODE_COLLATERAL: + collateral_vout = vout_idx + self.nodes[0].lockunspent(False, + [{"txid": txid, "vout": collateral_vout}]) + self.mninfo.append(MasternodeInfo(key, txid, collateral_vout)) + + def write_mn_config(self): + conf = self.get_mnconf_file() + f = open(conf, 'a') + for idx in range(0, self.mn_count): + f.write("mn%d 127.0.0.1:%d %s %s %d\n" % (idx + 1, p2p_port(idx + 1), + self.mninfo[idx].key, + self.mninfo[idx].collateral_id, + self.mninfo[idx].collateral_out)) + f.close() + + def create_masternodes(self): + for idx in range(0, self.mn_count): + self.nodes.append(start_node(idx + 1, self.options.tmpdir, + ['-debug=masternode', '-externalip=127.0.0.1', + '-masternode=1', + '-masternodeprivkey=%s' % self.mninfo[idx].key + ])) + for i in range(0, idx + 1): + connect_nodes(self.nodes[i], idx + 1) + + def sentinel(self): + for i in range(1, self.mn_count + 1): + self.nodes[i].sentinelping("1.1.0") + + def setup_network(self): + self.nodes = [] + # create faucet node for collateral and transactions + self.nodes.append(start_node(0, self.options.tmpdir, ["-debug"])) + required_balance = MASTERNODE_COLLATERAL * self.mn_count + 1 + while self.nodes[0].getbalance() < required_balance: + set_mocktime(get_mocktime() + 1) + self.nodes[0].generate(1) + # create masternodes + self.prepare_masternodes() + self.write_mn_config() + stop_node(self.nodes[0], 0) + self.nodes[0] = start_node(0, self.options.tmpdir, ["-debug"]) + self.create_masternodes() + # create connected simple nodes + for i in range(0, self.num_nodes - self.mn_count - 1): + self.create_simple_node() + # feed the sender with some balance + sender_addr = self.nodes[self.sender_idx].getnewaddress() + self.nodes[0].sendtoaddress(sender_addr, 1) + # make sender funds mature for InstantSend + for i in range(0, 2): + set_mocktime(get_mocktime() + 1) + self.nodes[0].generate(1) + # sync nodes + self.sync_all() + set_mocktime(get_mocktime() + 1) + sync_masternodes(self.nodes) + for i in range(1, self.mn_count + 1): + res = self.nodes[0].masternode("start-alias", "mn%d" % i) + assert(res["result"] == 'successful') + sync_masternodes(self.nodes) + #self.sentinel() + mn_info = self.nodes[0].masternodelist("status") + assert(len(mn_info) == self.mn_count) + for status in mn_info.values(): + assert(status == 'ENABLED') + + def create_raw_trx(self, node_from, node_to, amount): + # fill inputs + inputs=[] + balances = node_from.listunspent() + for tx in balances: + if tx['amount'] > amount: + input = {} + input["txid"] = tx['txid'] + input['vout'] = tx['vout'] + in_amount = float(tx['amount']) + inputs.append(input) + break + assert(len(inputs) > 0) + # fill outputs + receiver_address = node_to.getnewaddress() + change_address = node_from.getnewaddress() + fee = 0.001 + outputs={} + outputs[receiver_address] = amount + outputs[change_address] = in_amount - amount - fee + rawtx = node_from.createrawtransaction(inputs, outputs) + return node_from.signrawtransaction(rawtx) + + def run_test(self): + # create doublepending transaction, but don't relay it + dblspnd_tx = self.create_raw_trx(self.nodes[self.sender_idx], + self.nodes[self.isolated_idx], + 0.5) + # stop one node to isolate it from network + stop_node(self.nodes[self.isolated_idx], self.isolated_idx) + # instantsend to receiver + receiver_addr = self.nodes[self.receiver_idx].getnewaddress() + is_id = self.nodes[self.sender_idx].instantsendtoaddress(receiver_addr, 0.9) + # wait for instantsend locks + start = time() + locked = False + while True: + is_trx = self.nodes[self.sender_idx].gettransaction(is_id) + if is_trx['instantlock']: + locked = True + break + if time() > start + 10: + break + assert(locked) + # start last node + self.nodes[self.isolated_idx] = start_node(self.isolated_idx, + self.options.tmpdir, + ["-debug"]) + # send doublespend transaction to isolated node + self.nodes[self.isolated_idx].sendrawtransaction(dblspnd_tx['hex']) + # generate block on isolated node with doublespend transaction + set_mocktime(get_mocktime() + 1) + self.nodes[self.isolated_idx].generate(1) + wrong_block = self.nodes[self.isolated_idx].getbestblockhash() + # connect isolated block to network + for i in range(0, self.isolated_idx): + connect_nodes(self.nodes[i], self.isolated_idx) + # check doublespend block is rejected by other nodes + timeout = 10 + for i in range(0, self.isolated_idx): + res = self.nodes[i].waitforblock(wrong_block, timeout) + assert (res['hash'] != wrong_block) + # wait for long time only for first node + timeout = 1 + + +if __name__ == '__main__': + InstantSendTest().main() diff --git a/qa/rpc-tests/test_framework/util.py b/qa/rpc-tests/test_framework/util.py index c18ce742c2a5..abd6bd0a8f60 100644 --- a/qa/rpc-tests/test_framework/util.py +++ b/qa/rpc-tests/test_framework/util.py @@ -30,7 +30,7 @@ COVERAGE_DIR = None # The maximum number of nodes a single test can spawn -MAX_NODES = 8 +MAX_NODES = 15 # Don't assign rpc or p2p ports lower than this PORT_MIN = 11000 # The number of ports to "reserve" for p2p and rpc, each diff --git a/src/chainparams.cpp b/src/chainparams.cpp index 622e998b7b52..95dca10b0936 100644 --- a/src/chainparams.cpp +++ b/src/chainparams.cpp @@ -38,7 +38,7 @@ static CBlock CreateGenesisBlock(const char* pszTimestamp, const CScript& genesi genesis.nBits = nBits; genesis.nNonce = nNonce; genesis.nVersion = nVersion; - + genesis.vtx.push_back(MakeTransactionRef(std::move(txNew))); genesis.hashPrevBlock.SetNull(); genesis.hashMerkleRoot = BlockMerkleRoot(genesis); @@ -151,8 +151,8 @@ class CMainParams : public CChainParams { consensus.nMasternodeMinimumConfirmations = 15; consensus.BIP34Height = 0; consensus.BIP34Hash = uint256S("0x00000de52875a68d7bf6a5bb5ad1b89fd7df4d67a9603669327949923dc74d7e"); - consensus.BIP65Height = 390000; - consensus.BIP66Height = 395000; + consensus.BIP65Height = 390000; + consensus.BIP66Height = 395000; consensus.DIP0001Height = 450000; consensus.powLimit = uint256S("00000fffff000000000000000000000000000000000000000000000000000000"); consensus.nPowTargetTimespan = 7.5 * 60; // 5 blocks @@ -235,6 +235,7 @@ class CMainParams : public CChainParams { fMiningRequiresPeers = true; fDefaultConsistencyChecks = false; fRequireStandard = true; + fRequireRoutableExternalIP = true; fMineBlocksOnDemand = false; fAllowMultipleAddressesFromGroup = false; fAllowMultiplePorts = false; @@ -251,7 +252,7 @@ class CMainParams : public CChainParams { ( 250000, uint256S("0x00000000000640d8897addd4200209b6dd754aa3ca1f39857f8f03f36a44cc02")) ( 300000, uint256S("0x00000000000abec2c4fe6aec36d3f37026df8ed8817789a43278392092fe9d1a")) ( 350400, uint256S("0x0000000000056195689db2edb979305163b7ed88c1e7ce8875bd2b5feb4c432d")) - + }; chainTxData = ChainTxData{ @@ -374,6 +375,7 @@ class CTestNetParams : public CChainParams { fMiningRequiresPeers = false; fDefaultConsistencyChecks = false; fRequireStandard = false; + fRequireRoutableExternalIP = true; fMineBlocksOnDemand = true; fAllowMultipleAddressesFromGroup = false; fAllowMultiplePorts = false; @@ -557,7 +559,7 @@ class CRegTestParams : public CChainParams { consensus.fPowAllowMinDifficultyBlocks = true; consensus.fPowNoRetargeting = true; - consensus.nPowDGWHeight = 25; + consensus.nPowDGWHeight = 25; consensus.nRuleChangeActivationThreshold = 108; // 75% for testchains consensus.nMinerConfirmationWindow = 144; // Faster than normal for regtest (144 instead of 2016) consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].bit = 28; @@ -601,6 +603,7 @@ class CRegTestParams : public CChainParams { fMiningRequiresPeers = false; fDefaultConsistencyChecks = true; fRequireStandard = false; + fRequireRoutableExternalIP = false; fMineBlocksOnDemand = true; fAllowMultipleAddressesFromGroup = true; fAllowMultiplePorts = true; diff --git a/src/chainparams.h b/src/chainparams.h index 2b9a27cd180b..1d77f2955592 100644 --- a/src/chainparams.h +++ b/src/chainparams.h @@ -69,6 +69,8 @@ class CChainParams bool DefaultConsistencyChecks() const { return fDefaultConsistencyChecks; } /** Policy: Filter transactions that do not match well-defined patterns */ bool RequireStandard() const { return fRequireStandard; } + /** Require addresses specified with "-externalip" parameter to be routable */ + bool RequireRoutableExternalIP() const { return fRequireRoutableExternalIP; } uint64_t PruneAfterHeight() const { return nPruneAfterHeight; } /** Make miner stop after a block is found. In RPC, don't return until nGenProcLimit blocks are generated */ bool MineBlocksOnDemand() const { return fMineBlocksOnDemand; } @@ -106,6 +108,7 @@ class CChainParams bool fMiningRequiresPeers; bool fDefaultConsistencyChecks; bool fRequireStandard; + bool fRequireRoutableExternalIP; bool fMineBlocksOnDemand; bool fAllowMultipleAddressesFromGroup; bool fAllowMultiplePorts; diff --git a/src/masternodeman.cpp b/src/masternodeman.cpp index 7c06d5b90f8f..e55bcf03d877 100644 --- a/src/masternodeman.cpp +++ b/src/masternodeman.cpp @@ -969,7 +969,9 @@ void CMasternodeMan::SyncAll(CNode* pnode, CConnman& connman) LOCK(cs); for (const auto& mnpair : mapMasternodes) { - if (mnpair.second.addr.IsRFC1918() || mnpair.second.addr.IsLocal()) continue; // do not send local network masternode + if (Params().RequireRoutableExternalIP() && + (mnpair.second.addr.IsRFC1918() || mnpair.second.addr.IsLocal())) + continue; // do not send local network masternode // NOTE: send masternode regardless of its current state, the other node will need it to verify old votes. LogPrint("masternode", "CMasternodeMan::%s -- Sending Masternode entry: masternode=%s addr=%s\n", __func__, mnpair.first.ToStringShort(), mnpair.second.addr.ToString()); PushDsegInvs(pnode, mnpair.second); diff --git a/src/net.cpp b/src/net.cpp index 1d67ac5a7bf3..c63126dd4fa0 100644 --- a/src/net.cpp +++ b/src/net.cpp @@ -206,7 +206,7 @@ void AdvertiseLocal(CNode *pnode) // learn a new local address bool AddLocal(const CService& addr, int nScore) { - if (!addr.IsRoutable()) + if (!addr.IsRoutable() && Params().RequireRoutableExternalIP()) return false; if (!fDiscover && nScore < LOCAL_MANUAL) From ef2760462a9825220eae246b4ca5dddb4d59aa69 Mon Sep 17 00:00:00 2001 From: PaulieD Date: Thu, 12 Jul 2018 04:05:39 -0500 Subject: [PATCH 009/282] GetOutPointPrivateSendRounds readability (#2149) * .gitnore visual studio bs * Improves the readability of the `GetOutpointPrivateSendRounds` function by not having the second argument be needed, as the second arg should only not be 0 when it is recursively calling itself * Revert ".gitnore visual studio bs" This reverts commit 129b5242ade6a97a71810f492b5b347be219b691. * changed back comment and fixed allignment * refactor based on Udjin's suggestions. * refactor based on Udjin's suggestions. * fix alignment * Revert "fix alignment" This reverts commit c2cc2ae531c191258cd043b2b45a316443e4b860. * actually fix alignment * actually fix alignment --- src/qt/coincontroldialog.cpp | 4 ++-- src/wallet/rpcwallet.cpp | 2 +- src/wallet/wallet.cpp | 20 ++++++++++---------- src/wallet/wallet.h | 4 ++-- 4 files changed, 15 insertions(+), 15 deletions(-) diff --git a/src/qt/coincontroldialog.cpp b/src/qt/coincontroldialog.cpp index 7184ffff4531..003342ca8dd2 100644 --- a/src/qt/coincontroldialog.cpp +++ b/src/qt/coincontroldialog.cpp @@ -434,7 +434,7 @@ void CoinControlDialog::viewItemChanged(QTreeWidgetItem* item, int column) item->setCheckState(COLUMN_CHECKBOX, Qt::Unchecked); else { coinControl->Select(outpt); - int nRounds = pwalletMain->GetOutpointPrivateSendRounds(outpt); + int nRounds = pwalletMain->GetCappedOutpointPrivateSendRounds(outpt); if (coinControl->fUsePrivateSend && nRounds < privateSendClient.nPrivateSendRounds) { QMessageBox::warning(this, windowTitle(), tr("Non-anonymized input selected. PrivateSend will be disabled.

If you still want to use PrivateSend, please deselect all non-nonymized inputs first and then check PrivateSend checkbox again."), @@ -782,7 +782,7 @@ void CoinControlDialog::updateView() // PrivateSend rounds COutPoint outpoint = COutPoint(out.tx->tx->GetHash(), out.i); - int nRounds = pwalletMain->GetOutpointPrivateSendRounds(outpoint); + int nRounds = pwalletMain->GetCappedOutpointPrivateSendRounds(outpoint); if (nRounds >= 0 || fDebug) itemOutput->setText(COLUMN_PRIVATESEND_ROUNDS, QString::number(nRounds)); else itemOutput->setText(COLUMN_PRIVATESEND_ROUNDS, tr("n/a")); diff --git a/src/wallet/rpcwallet.cpp b/src/wallet/rpcwallet.cpp index cf34ad6bfdd0..9fe2db850f5b 100644 --- a/src/wallet/rpcwallet.cpp +++ b/src/wallet/rpcwallet.cpp @@ -2648,7 +2648,7 @@ UniValue listunspent(const JSONRPCRequest& request) entry.push_back(Pair("confirmations", out.nDepth)); entry.push_back(Pair("spendable", out.fSpendable)); entry.push_back(Pair("solvable", out.fSolvable)); - entry.push_back(Pair("ps_rounds", pwalletMain->GetOutpointPrivateSendRounds(COutPoint(out.tx->GetHash(), out.i)))); + entry.push_back(Pair("ps_rounds", pwalletMain->GetCappedOutpointPrivateSendRounds(COutPoint(out.tx->GetHash(), out.i)))); results.push_back(entry); } diff --git a/src/wallet/wallet.cpp b/src/wallet/wallet.cpp index ef1ab4a27a46..3a9a3c8790df 100644 --- a/src/wallet/wallet.cpp +++ b/src/wallet/wallet.cpp @@ -1505,10 +1505,10 @@ int CWallet::GetRealOutpointPrivateSendRounds(const COutPoint& outpoint, int nRo } // respect current settings -int CWallet::GetOutpointPrivateSendRounds(const COutPoint& outpoint) const +int CWallet::GetCappedOutpointPrivateSendRounds(const COutPoint& outpoint) const { LOCK(cs_wallet); - int realPrivateSendRounds = GetRealOutpointPrivateSendRounds(outpoint, 0); + int realPrivateSendRounds = GetRealOutpointPrivateSendRounds(outpoint); return realPrivateSendRounds > privateSendClient.nPrivateSendRounds ? privateSendClient.nPrivateSendRounds : realPrivateSendRounds; } @@ -2171,7 +2171,7 @@ CAmount CWalletTx::GetAnonymizedCredit(bool fUseCache) const if(pwallet->IsSpent(hashTx, i) || !pwallet->IsDenominated(outpoint)) continue; - const int nRounds = pwallet->GetOutpointPrivateSendRounds(outpoint); + const int nRounds = pwallet->GetCappedOutpointPrivateSendRounds(outpoint); if(nRounds >= privateSendClient.nPrivateSendRounds){ nCredit += pwallet->GetCredit(txout, ISMINE_SPENDABLE); if (!MoneyRange(nCredit)) @@ -2419,7 +2419,7 @@ float CWallet::GetAverageAnonymizedRounds() const for (const auto& outpoint : setWalletUTXO) { if(!IsDenominated(outpoint)) continue; - nTotal += GetOutpointPrivateSendRounds(outpoint); + nTotal += GetCappedOutpointPrivateSendRounds(outpoint); nCount++; } @@ -2443,7 +2443,7 @@ CAmount CWallet::GetNormalizedAnonymizedBalance() const if (!IsDenominated(outpoint)) continue; if (it->second.GetDepthInMainChain() < 0) continue; - int nRounds = GetOutpointPrivateSendRounds(outpoint); + int nRounds = GetCappedOutpointPrivateSendRounds(outpoint); nTotal += it->second.tx->vout[outpoint.n].nValue * nRounds / privateSendClient.nPrivateSendRounds; } @@ -2844,7 +2844,7 @@ bool CWallet::SelectCoins(const std::vector& vAvailableCoins, const CAm if(nCoinType == ONLY_DENOMINATED) { COutPoint outpoint = COutPoint(out.tx->GetHash(),out.i); - int nRounds = GetOutpointPrivateSendRounds(outpoint); + int nRounds = GetCappedOutpointPrivateSendRounds(outpoint); // make sure it's actually anonymized if(nRounds < privateSendClient.nPrivateSendRounds) continue; } @@ -2867,7 +2867,7 @@ bool CWallet::SelectCoins(const std::vector& vAvailableCoins, const CAm //make sure it's the denom we're looking for, round the amount up to smallest denom if(out.tx->tx->vout[out.i].nValue == nDenom && nValueRet + nDenom < nTargetValue + nSmallestDenom) { COutPoint outpoint = COutPoint(out.tx->GetHash(),out.i); - int nRounds = GetOutpointPrivateSendRounds(outpoint); + int nRounds = GetCappedOutpointPrivateSendRounds(outpoint); // make sure it's actually anonymized if(nRounds < privateSendClient.nPrivateSendRounds) continue; nValueRet += nDenom; @@ -3027,7 +3027,7 @@ bool CWallet::SelectCoinsByDenominations(int nDenom, CAmount nValueMin, CAmount CTxIn txin = CTxIn(out.tx->GetHash(), out.i); - int nRounds = GetOutpointPrivateSendRounds(txin.prevout); + int nRounds = GetCappedOutpointPrivateSendRounds(txin.prevout); if(nRounds >= nPrivateSendRoundsMax) continue; if(nRounds < nPrivateSendRoundsMin) continue; @@ -3111,7 +3111,7 @@ bool CWallet::SelectCoinsGrouppedByAddresses(std::vector& vecT // otherwise they will just lead to higher fee / lower priority if(wtx.tx->vout[i].nValue <= nSmallestDenom/10) continue; // ignore anonymized - if(GetOutpointPrivateSendRounds(COutPoint(outpoint.hash, i)) >= privateSendClient.nPrivateSendRounds) continue; + if(GetCappedOutpointPrivateSendRounds(COutPoint(outpoint.hash, i)) >= privateSendClient.nPrivateSendRounds) continue; } CompactTallyItem& item = mapTally[txdest]; @@ -3177,7 +3177,7 @@ bool CWallet::SelectCoinsDark(CAmount nValueMin, CAmount nValueMax, std::vector< if(nValueRet + out.tx->tx->vout[out.i].nValue <= nValueMax){ CTxIn txin = CTxIn(out.tx->GetHash(),out.i); - int nRounds = GetOutpointPrivateSendRounds(txin.prevout); + int nRounds = GetCappedOutpointPrivateSendRounds(txin.prevout); if(nRounds >= nPrivateSendRoundsMax) continue; if(nRounds < nPrivateSendRoundsMin) continue; diff --git a/src/wallet/wallet.h b/src/wallet/wallet.h index 2448aeafbf5a..43af83bd055a 100644 --- a/src/wallet/wallet.h +++ b/src/wallet/wallet.h @@ -820,9 +820,9 @@ class CWallet : public CCryptoKeyStore, public CValidationInterface int CountInputsWithAmount(CAmount nInputAmount); // get the PrivateSend chain depth for a given input - int GetRealOutpointPrivateSendRounds(const COutPoint& outpoint, int nRounds) const; + int GetRealOutpointPrivateSendRounds(const COutPoint& outpoint, int nRounds = 0) const; // respect current settings - int GetOutpointPrivateSendRounds(const COutPoint& outpoint) const; + int GetCappedOutpointPrivateSendRounds(const COutPoint& outpoint) const; bool IsDenominated(const COutPoint& outpoint) const; From 37cc6698780955987ac954c9e2b7594072a4b7ae Mon Sep 17 00:00:00 2001 From: PaulieD Date: Thu, 12 Jul 2018 04:06:30 -0500 Subject: [PATCH 010/282] Implement Governance ZMQ notification messages (#2160) * fix whitespace * added zmq stuff for governance objects and votes it seems that zmq is currently not in a working state, need to figure that out. Need to: plug in the new methods added possibly plug in the old methods, as it doesn't look like they are. * formatting fix. Will probably need to revert for this PR * continue linking new zmq messages in * added comment, might need to revert * fixes error of it not knowing about the classes * Actually link in, all new govobjects and govvotes should be broadcast over zmq now. * fix compile error, forgot to change params when copying * fix compile error * add imports to the header files in zmqconfig.h * fixing linking(i think) error * Revert "added comment, might need to revert" This reverts commit 2918ea40fe9a96834c4bd89e13cb458cde6814f2. * Revert "formatting fix. Will probably need to revert for this PR" This reverts commit ca10558866ab61e3dd0c70541fdcfee6f5115157. * fix tabs etc * EOL added * optimization of hash.begin() @nmarley thoughts? * remove formatting changes * iterator i -> it and removal of notifier * typo in df879f57 * use auto for the iterators * introduce hash prefix * implement changes in zmq_sub.py, update the doc, and change argument name to fix typo * deref iterators before calling methods * continued e8a4c505 * missed one... continued e8a4c505 * killing some tabs * fix spacing for setting or comparing iterators * change order of new variables to match current setup * re-add elif's I didn't realize got removed * Revert "fix spacing for setting or comparing iterators" This reverts commit 8ce2068148dcd275ebba7ee6038d0db1c582b9f3. * Revert "use auto for the iterators" This reverts commit cb16cf0760bfaf68c56684877898611802bf2303. * Revert "missed one... continued e8a4c505" This reverts commit 2087cf894f7e9682508b4692b89897b4fa4e4b7a. * Revert "continued e8a4c505" This reverts commit a78c8ad2c9bb1602242a8f040e17ef958982348c. * Revert "deref iterators before calling methods" This reverts commit e8a4c505d1d34360eaf882d92cd8fbc55436cfcc. * Revert "iterator i -> it and removal of notifier" This reverts commit 29574248b1a0d05c18d60454d07c77979aae6fb2. * Revert "fix whitespace" This reverts commit 612be48d963000b4cbc5f64981a88a3225428b37. * Revert "typo in df879f5" * Revert "Optimization of hash.begin()" * fixes problem with revert * Udjin complain's a lot ;) * help text, init.cpp * add signals in validationinterface.cpp * Change location of vote notification call. * remain consistent * remove unneeded include due to change of notification location * implement raw notifications --- contrib/zmq/zmq_sub.py | 17 +++++++++++ doc/zmq.md | 4 +++ src/governance.cpp | 8 +++++- src/init.cpp | 2 ++ src/validationinterface.cpp | 6 ++++ src/validationinterface.h | 8 ++++++ src/zmq/zmqabstractnotifier.cpp | 10 +++++++ src/zmq/zmqabstractnotifier.h | 5 ++++ src/zmq/zmqconfig.h | 3 ++ src/zmq/zmqnotificationinterface.cpp | 38 +++++++++++++++++++++++++ src/zmq/zmqnotificationinterface.h | 3 ++ src/zmq/zmqpublishnotifier.cpp | 42 ++++++++++++++++++++++++++++ src/zmq/zmqpublishnotifier.h | 25 +++++++++++++++++ 13 files changed, 170 insertions(+), 1 deletion(-) diff --git a/contrib/zmq/zmq_sub.py b/contrib/zmq/zmq_sub.py index 47087e875b59..7fbfbbd005e6 100755 --- a/contrib/zmq/zmq_sub.py +++ b/contrib/zmq/zmq_sub.py @@ -14,9 +14,13 @@ zmqSubSocket.setsockopt(zmq.SUBSCRIBE, b"hashblock") zmqSubSocket.setsockopt(zmq.SUBSCRIBE, b"hashtx") zmqSubSocket.setsockopt(zmq.SUBSCRIBE, b"hashtxlock") +zmqSubSocket.setsockopt(zmq.SUBSCRIBE, b"hashgovernancevote") +zmqSubSocket.setsockopt(zmq.SUBSCRIBE, b"hashgovernanceobject") zmqSubSocket.setsockopt(zmq.SUBSCRIBE, b"rawblock") zmqSubSocket.setsockopt(zmq.SUBSCRIBE, b"rawtx") zmqSubSocket.setsockopt(zmq.SUBSCRIBE, b"rawtxlock") +zmqSubSocket.setsockopt(zmq.SUBSCRIBE, b"rawgovernancevote") +zmqSubSocket.setsockopt(zmq.SUBSCRIBE, b"rawgovernanceobject") zmqSubSocket.connect("tcp://127.0.0.1:%i" % port) try: @@ -48,6 +52,19 @@ elif topic == "rawtxlock": print('- RAW TX LOCK ('+sequence+') -') print(binascii.hexlify(body).decode("utf-8")) + elif topic == "hashgovernancevote": + print('- HASH GOVERNANCE VOTE ('+sequence+') -') + print(binascii.hexlify(body).decode("utf-8")) + elif topic == "hashgovernanceobject": + print('- HASH GOVERNANCE OBJECT ('+sequence+') -') + print(binascii.hexlify(body).decode("utf-8")) + elif topic == "rawgovernancevote": + print('- RAW GOVERNANCE VOTE ('+sequence+') -') + print(binascii.hexlify(body).decode("utf-8")) + elif topic == "rawgovernanceobject": + print('- RAW GOVERNANCE OBJECT ('+sequence+') -') + print(binascii.hexlify(body).decode("utf-8")) + except KeyboardInterrupt: zmqContext.destroy() diff --git a/doc/zmq.md b/doc/zmq.md index a5f695801141..3667a52f5fa2 100644 --- a/doc/zmq.md +++ b/doc/zmq.md @@ -62,6 +62,10 @@ Currently, the following notifications are supported: -zmqpubrawblock=address -zmqpubrawtx=address -zmqpubrawtxlock=address + -zmqpubhashgovernancevote=address + -zmqpubhashgovernanceobject=address + -zmqpubrawgovernancevote=address + -zmqpubhashgovernanceobject=address The socket type is PUB and the address must be a valid ZeroMQ socket address. The same address can be used in more than one notification. diff --git a/src/governance.cpp b/src/governance.cpp index 2626f039b636..a111b9a0b538 100644 --- a/src/governance.cpp +++ b/src/governance.cpp @@ -4,6 +4,7 @@ // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "consensus/validation.h" +#include "validationinterface.h" #include "governance.h" #include "governance-object.h" #include "governance-validators.h" @@ -266,7 +267,8 @@ void CGovernanceManager::ProcessMessage(CNode* pfrom, const std::string& strComm } return; } - + // SEND NOTIFICATION TO SCRIPT/ZMQ + GetMainSignals().NotifyGovernanceVote(vote); } } @@ -363,6 +365,10 @@ void CGovernanceManager::AddGovernanceObject(CGovernanceObject& govobj, CConnman CGovernanceException exception; CheckOrphanVotes(govobj, exception, connman); + // SEND NOTIFICATION TO SCRIPT/ZMQ + GetMainSignals().NotifyGovernanceObject(govobj); + + DBG( std::cout << "CGovernanceManager::AddGovernanceObject END" << std::endl; ); } diff --git a/src/init.cpp b/src/init.cpp index 0a71e69d292c..17813d18c05d 100644 --- a/src/init.cpp +++ b/src/init.cpp @@ -490,6 +490,8 @@ std::string HelpMessage(HelpMessageMode mode) strUsage += HelpMessageOpt("-zmqpubhashblock=
", _("Enable publish hash block in
")); strUsage += HelpMessageOpt("-zmqpubhashtx=
", _("Enable publish hash transaction in
")); strUsage += HelpMessageOpt("-zmqpubhashtxlock=
", _("Enable publish hash transaction (locked via InstantSend) in
")); + strUsage += HelpMessageOpt("-zmqpubhashgovernancevote=
", _("Enable publish hash of governance votes in
")); + strUsage += HelpMessageOpt("-zmqpubhashgovernanceobject=
", _("Enable publish hash of governance objects (like proposals) in
")); strUsage += HelpMessageOpt("-zmqpubrawblock=
", _("Enable publish raw block in
")); strUsage += HelpMessageOpt("-zmqpubrawtx=
", _("Enable publish raw transaction in
")); strUsage += HelpMessageOpt("-zmqpubrawtxlock=
", _("Enable publish raw transaction (locked via InstantSend) in
")); diff --git a/src/validationinterface.cpp b/src/validationinterface.cpp index 56620c929479..436cedf1019c 100644 --- a/src/validationinterface.cpp +++ b/src/validationinterface.cpp @@ -26,6 +26,8 @@ void RegisterValidationInterface(CValidationInterface* pwalletIn) { g_signals.ScriptForMining.connect(boost::bind(&CValidationInterface::GetScriptForMining, pwalletIn, _1)); g_signals.BlockFound.connect(boost::bind(&CValidationInterface::ResetRequestCount, pwalletIn, _1)); g_signals.NewPoWValidBlock.connect(boost::bind(&CValidationInterface::NewPoWValidBlock, pwalletIn, _1, _2)); + g_signals.NotifyGovernanceObject.connect(boost::bind(&CValidationInterface::NotifyGovernanceObject, pwalletIn, _1)); + g_signals.NotifyGovernanceVote.connect(boost::bind(&CValidationInterface::NotifyGovernanceVote, pwalletIn, _1)); } void UnregisterValidationInterface(CValidationInterface* pwalletIn) { @@ -42,6 +44,8 @@ void UnregisterValidationInterface(CValidationInterface* pwalletIn) { g_signals.NewPoWValidBlock.disconnect(boost::bind(&CValidationInterface::NewPoWValidBlock, pwalletIn, _1, _2)); g_signals.NotifyHeaderTip.disconnect(boost::bind(&CValidationInterface::NotifyHeaderTip, pwalletIn, _1, _2)); g_signals.AcceptedBlockHeader.disconnect(boost::bind(&CValidationInterface::AcceptedBlockHeader, pwalletIn, _1)); + g_signals.NotifyGovernanceObject.disconnect(boost::bind(&CValidationInterface::NotifyGovernanceObject, pwalletIn, _1)); + g_signals.NotifyGovernanceVote.disconnect(boost::bind(&CValidationInterface::NotifyGovernanceVote, pwalletIn, _1)); } void UnregisterAllValidationInterfaces() { @@ -58,4 +62,6 @@ void UnregisterAllValidationInterfaces() { g_signals.NewPoWValidBlock.disconnect_all_slots(); g_signals.NotifyHeaderTip.disconnect_all_slots(); g_signals.AcceptedBlockHeader.disconnect_all_slots(); + g_signals.NotifyGovernanceObject.disconnect_all_slots(); + g_signals.NotifyGovernanceVote.disconnect_all_slots(); } diff --git a/src/validationinterface.h b/src/validationinterface.h index 7086840c7347..8ce15b30cd5f 100644 --- a/src/validationinterface.h +++ b/src/validationinterface.h @@ -18,6 +18,8 @@ class CReserveScript; class CTransaction; class CValidationInterface; class CValidationState; +class CGovernanceVote; +class CGovernanceObject; class uint256; // These functions dispatch to one or all registered wallets @@ -36,6 +38,8 @@ class CValidationInterface { virtual void UpdatedBlockTip(const CBlockIndex *pindexNew, const CBlockIndex *pindexFork, bool fInitialDownload) {} virtual void SyncTransaction(const CTransaction &tx, const CBlockIndex *pindex, int posInBlock) {} virtual void NotifyTransactionLock(const CTransaction &tx) {} + virtual void NotifyGovernanceVote(const CGovernanceVote &vote) {} + virtual void NotifyGovernanceObject(const CGovernanceObject &object) {} virtual void SetBestChain(const CBlockLocator &locator) {} virtual bool UpdatedTransaction(const uint256 &hash) { return false;} virtual void Inventory(const uint256 &hash) {} @@ -69,6 +73,10 @@ struct CMainSignals { boost::signals2::signal SyncTransaction; /** Notifies listeners of an updated transaction lock without new data. */ boost::signals2::signal NotifyTransactionLock; + /** Notifies listeners of a new governance vote. */ + boost::signals2::signal NotifyGovernanceVote; + /** Notifies listeners of a new governance object. */ + boost::signals2::signal NotifyGovernanceObject; /** Notifies listeners of an updated transaction without new data (for now: a coinbase potentially becoming visible). */ boost::signals2::signal UpdatedTransaction; /** Notifies listeners of a new active block chain. */ diff --git a/src/zmq/zmqabstractnotifier.cpp b/src/zmq/zmqabstractnotifier.cpp index 76543a4a797a..ea993d6061bc 100644 --- a/src/zmq/zmqabstractnotifier.cpp +++ b/src/zmq/zmqabstractnotifier.cpp @@ -25,3 +25,13 @@ bool CZMQAbstractNotifier::NotifyTransactionLock(const CTransaction &/*transacti { return true; } + +bool CZMQAbstractNotifier::NotifyGovernanceVote(const CGovernanceVote& /*vote*/) +{ + return true; +} + +bool CZMQAbstractNotifier::NotifyGovernanceObject(const CGovernanceObject& /*object*/) +{ + return true; +} diff --git a/src/zmq/zmqabstractnotifier.h b/src/zmq/zmqabstractnotifier.h index 0d3f1fcd4e41..ee6aa3ad7e2c 100644 --- a/src/zmq/zmqabstractnotifier.h +++ b/src/zmq/zmqabstractnotifier.h @@ -8,6 +8,8 @@ #include "zmqconfig.h" class CBlockIndex; +class CGovernanceObject; +class CGovernanceVote; class CZMQAbstractNotifier; typedef CZMQAbstractNotifier* (*CZMQNotifierFactory)(); @@ -35,6 +37,9 @@ class CZMQAbstractNotifier virtual bool NotifyBlock(const CBlockIndex *pindex); virtual bool NotifyTransaction(const CTransaction &transaction); virtual bool NotifyTransactionLock(const CTransaction &transaction); + virtual bool NotifyGovernanceVote(const CGovernanceVote &vote); + virtual bool NotifyGovernanceObject(const CGovernanceObject &object); + protected: void *psocket; diff --git a/src/zmq/zmqconfig.h b/src/zmq/zmqconfig.h index 66f6e7476e43..c94035fd6dad 100644 --- a/src/zmq/zmqconfig.h +++ b/src/zmq/zmqconfig.h @@ -19,6 +19,9 @@ #include "primitives/block.h" #include "primitives/transaction.h" +#include "governance-object.h" +#include "governance-vote.h" + void zmqError(const char *str); #endif // BITCOIN_ZMQ_ZMQCONFIG_H diff --git a/src/zmq/zmqnotificationinterface.cpp b/src/zmq/zmqnotificationinterface.cpp index 475c0251bc07..7895f17aaa8b 100644 --- a/src/zmq/zmqnotificationinterface.cpp +++ b/src/zmq/zmqnotificationinterface.cpp @@ -38,9 +38,13 @@ CZMQNotificationInterface* CZMQNotificationInterface::Create() factories["pubhashblock"] = CZMQAbstractNotifier::Create; factories["pubhashtx"] = CZMQAbstractNotifier::Create; factories["pubhashtxlock"] = CZMQAbstractNotifier::Create; + factories["pubhashgovernancevote"] = CZMQAbstractNotifier::Create; + factories["pubhashgovernanceobject"] = CZMQAbstractNotifier::Create; factories["pubrawblock"] = CZMQAbstractNotifier::Create; factories["pubrawtx"] = CZMQAbstractNotifier::Create; factories["pubrawtxlock"] = CZMQAbstractNotifier::Create; + factories["pubrawgovernancevote"] = CZMQAbstractNotifier::Create; + factories["pubrawgovernanceobject"] = CZMQAbstractNotifier::Create; for (std::map::const_iterator i=factories.begin(); i!=factories.end(); ++i) { @@ -179,3 +183,37 @@ void CZMQNotificationInterface::NotifyTransactionLock(const CTransaction &tx) } } } + +void CZMQNotificationInterface::NotifyGovernanceVote(const CGovernanceVote &vote) +{ + for (std::list::iterator i = notifiers.begin(); i != notifiers.end(); ) + { + CZMQAbstractNotifier *notifier = *i; + if (notifier->NotifyGovernanceVote(vote)) + { + i++; + } + else + { + notifier->Shutdown(); + i = notifiers.erase(i); + } + } +} + +void CZMQNotificationInterface::NotifyGovernanceObject(const CGovernanceObject &object) +{ + for (std::list::iterator i = notifiers.begin(); i != notifiers.end(); ) + { + CZMQAbstractNotifier *notifier = *i; + if (notifier->NotifyGovernanceObject(object)) + { + i++; + } + else + { + notifier->Shutdown(); + i = notifiers.erase(i); + } + } +} diff --git a/src/zmq/zmqnotificationinterface.h b/src/zmq/zmqnotificationinterface.h index 13b5c8bf96ed..aeaed254a007 100644 --- a/src/zmq/zmqnotificationinterface.h +++ b/src/zmq/zmqnotificationinterface.h @@ -27,6 +27,9 @@ class CZMQNotificationInterface : public CValidationInterface void SyncTransaction(const CTransaction& tx, const CBlockIndex *pindex, int posInBlock) override; void UpdatedBlockTip(const CBlockIndex *pindexNew, const CBlockIndex *pindexFork, bool fInitialDownload) override; void NotifyTransactionLock(const CTransaction &tx) override; + void NotifyGovernanceVote(const CGovernanceVote& vote) override; + void NotifyGovernanceObject(const CGovernanceObject& object) override; + private: CZMQNotificationInterface(); diff --git a/src/zmq/zmqpublishnotifier.cpp b/src/zmq/zmqpublishnotifier.cpp index be1f7ac0adfb..8a6c4167d0c8 100644 --- a/src/zmq/zmqpublishnotifier.cpp +++ b/src/zmq/zmqpublishnotifier.cpp @@ -13,9 +13,13 @@ static std::multimap mapPublishNotifi static const char *MSG_HASHBLOCK = "hashblock"; static const char *MSG_HASHTX = "hashtx"; static const char *MSG_HASHTXLOCK = "hashtxlock"; +static const char *MSG_HASHGVOTE = "hashgovernancevote"; +static const char *MSG_HASHGOBJ = "hashgovernanceobject"; static const char *MSG_RAWBLOCK = "rawblock"; static const char *MSG_RAWTX = "rawtx"; static const char *MSG_RAWTXLOCK = "rawtxlock"; +static const char *MSG_RAWGVOTE = "rawgovernancevote"; +static const char *MSG_RAWGOBJ = "rawgovernanceobject"; // Internal function to send multipart message static int zmq_send_multipart(void *sock, const void* data, size_t size, ...) @@ -173,6 +177,26 @@ bool CZMQPublishHashTransactionLockNotifier::NotifyTransactionLock(const CTransa return SendMessage(MSG_HASHTXLOCK, data, 32); } +bool CZMQPublishHashGovernanceVoteNotifier::NotifyGovernanceVote(const CGovernanceVote &vote) +{ + uint256 hash = vote.GetHash(); + LogPrint("zmq", "zmq: Publish hashgovernancevote %s\n", hash.GetHex()); + char data[32]; + for (unsigned int i = 0; i < 32; i++) + data[31 - i] = hash.begin()[i]; + return SendMessage(MSG_HASHGVOTE, data, 32); +} + +bool CZMQPublishHashGovernanceObjectNotifier::NotifyGovernanceObject(const CGovernanceObject &object) +{ + uint256 hash = object.GetHash(); + LogPrint("zmq", "zmq: Publish hashgovernanceobject %s\n", hash.GetHex()); + char data[32]; + for (unsigned int i = 0; i < 32; i++) + data[31 - i] = hash.begin()[i]; + return SendMessage(MSG_HASHGOBJ, data, 32); +} + bool CZMQPublishRawBlockNotifier::NotifyBlock(const CBlockIndex *pindex) { LogPrint("zmq", "zmq: Publish rawblock %s\n", pindex->GetBlockHash().GetHex()); @@ -211,3 +235,21 @@ bool CZMQPublishRawTransactionLockNotifier::NotifyTransactionLock(const CTransac ss << transaction; return SendMessage(MSG_RAWTXLOCK, &(*ss.begin()), ss.size()); } + +bool CZMQPublishRawGovernanceVoteNotifier::NotifyGovernanceVote(const CGovernanceVote &vote) +{ + uint256 nHash = vote.GetHash(); + LogPrint("gobject", "gobject: Publish rawgovernanceobject: hash = %s, vote = %d\n", nHash.ToString(), vote.ToString()); + CDataStream ss(SER_NETWORK, PROTOCOL_VERSION); + ss << vote; + return SendMessage(MSG_RAWGVOTE, &(*ss.begin()), ss.size()); +} + +bool CZMQPublishRawGovernanceObjectNotifier::NotifyGovernanceObject(const CGovernanceObject &govobj) +{ + uint256 nHash = govobj.GetHash(); + LogPrint("gobject", "gobject: Publish rawgovernanceobject: hash = %s, type = %d\n", nHash.ToString(), govobj.GetObjectType()); + CDataStream ss(SER_NETWORK, PROTOCOL_VERSION); + ss << govobj; + return SendMessage(MSG_RAWGOBJ, &(*ss.begin()), ss.size()); +} diff --git a/src/zmq/zmqpublishnotifier.h b/src/zmq/zmqpublishnotifier.h index 4ade12cdceac..31c90317d8c0 100644 --- a/src/zmq/zmqpublishnotifier.h +++ b/src/zmq/zmqpublishnotifier.h @@ -8,6 +8,8 @@ #include "zmqabstractnotifier.h" class CBlockIndex; +class CGovernanceVote; +class CGovernanceObject; class CZMQAbstractPublishNotifier : public CZMQAbstractNotifier { @@ -46,6 +48,18 @@ class CZMQPublishHashTransactionLockNotifier : public CZMQAbstractPublishNotifie bool NotifyTransactionLock(const CTransaction &transaction) override; }; +class CZMQPublishHashGovernanceVoteNotifier : public CZMQAbstractPublishNotifier +{ +public: + bool NotifyGovernanceVote(const CGovernanceVote &vote) override; +}; + +class CZMQPublishHashGovernanceObjectNotifier : public CZMQAbstractPublishNotifier +{ +public: + bool NotifyGovernanceObject(const CGovernanceObject &object) override; +}; + class CZMQPublishRawBlockNotifier : public CZMQAbstractPublishNotifier { public: @@ -64,4 +78,15 @@ class CZMQPublishRawTransactionLockNotifier : public CZMQAbstractPublishNotifier bool NotifyTransactionLock(const CTransaction &transaction) override; }; +class CZMQPublishRawGovernanceVoteNotifier : public CZMQAbstractPublishNotifier +{ +public: + bool NotifyGovernanceVote(const CGovernanceVote &vote) override; +}; + +class CZMQPublishRawGovernanceObjectNotifier : public CZMQAbstractPublishNotifier +{ +public: + bool NotifyGovernanceObject(const CGovernanceObject &object) override; +}; #endif // BITCOIN_ZMQ_ZMQPUBLISHNOTIFIER_H From 320fb4ceec2c075c4e003d493add2a610949f125 Mon Sep 17 00:00:00 2001 From: Nathan Marley Date: Thu, 12 Jul 2018 16:07:51 +0700 Subject: [PATCH 011/282] iterator cleanup in several places (#2164) * iterator cleanup in Dash-specific code * const * *Pair/pair * it++ -> ++it --- src/governance-classes.cpp | 10 +-- src/governance.cpp | 72 ++++++++++------------ src/instantx.cpp | 117 +++++++++++++----------------------- src/masternode-payments.cpp | 15 ++--- src/masternodeman.cpp | 23 +++---- src/privatesend-client.cpp | 3 +- src/privatesend.cpp | 4 +- src/spork.cpp | 8 +-- 8 files changed, 98 insertions(+), 154 deletions(-) diff --git a/src/governance-classes.cpp b/src/governance-classes.cpp index e9a85f580343..23128c21eae7 100644 --- a/src/governance-classes.cpp +++ b/src/governance-classes.cpp @@ -240,16 +240,12 @@ std::vector CGovernanceTriggerManager::GetActiveTriggers() DBG( std::cout << "GetActiveTriggers: mapTrigger.size() = " << mapTrigger.size() << std::endl; ); // LOOK AT THESE OBJECTS AND COMPILE A VALID LIST OF TRIGGERS - trigger_m_it it = mapTrigger.begin(); - while(it != mapTrigger.end()) { - - CGovernanceObject* pObj = governance.FindGovernanceObject((*it).first); - + for (const auto& pair : mapTrigger) { + CGovernanceObject* pObj = governance.FindGovernanceObject(pair.first); if(pObj) { DBG( std::cout << "GetActiveTriggers: pObj->GetDataAsPlainString() = " << pObj->GetDataAsPlainString() << std::endl; ); - vecResults.push_back(it->second); + vecResults.push_back(pair.second); } - ++it; } DBG( std::cout << "GetActiveTriggers: vecResults.size() = " << vecResults.size() << std::endl; ); diff --git a/src/governance.cpp b/src/governance.cpp index a111b9a0b538..f30251714a29 100644 --- a/src/governance.cpp +++ b/src/governance.cpp @@ -532,10 +532,10 @@ std::vector CGovernanceManager::GetCurrentVotes(const uint256& vote_rec_t voteRecord; if (!govobj.GetCurrentMNVotes(mnpair.first, voteRecord)) continue; - for (vote_instance_m_it it3 = voteRecord.mapInstances.begin(); it3 != voteRecord.mapInstances.end(); ++it3) { - int signal = (it3->first); - int outcome = ((it3->second).eOutcome); - int64_t nCreationTime = ((it3->second).nCreationTime); + for (const auto& voteInstancePair : voteRecord.mapInstances) { + int signal = voteInstancePair.first; + int outcome = voteInstancePair.second.eOutcome; + int64_t nCreationTime = voteInstancePair.second.nCreationTime; CGovernanceVote vote = CGovernanceVote(mnpair.first, nParentHash, (vote_signal_enum_t)signal, (vote_outcome_enum_t)outcome); vote.SetTime(nCreationTime); @@ -553,24 +553,15 @@ std::vector CGovernanceManager::GetAllNewerThan(int64_ std::vector vGovObjs; - object_m_cit it = mapObjects.begin(); - while(it != mapObjects.end()) - { + for (const auto& objPair : mapObjects) { // IF THIS OBJECT IS OLDER THAN TIME, CONTINUE - - if((*it).second.GetCreationTime() < nMoreThanTime) { - ++it; + if(objPair.second.GetCreationTime() < nMoreThanTime) { continue; } // ADD GOVERNANCE OBJECT TO LIST - - const CGovernanceObject* pGovObj = &((*it).second); + const CGovernanceObject* pGovObj = &(objPair.second); vGovObjs.push_back(pGovObj); - - // NEXT - - ++it; } return vGovObjs; @@ -732,9 +723,10 @@ void CGovernanceManager::SyncAll(CNode* pnode, CConnman& connman) const LOCK2(cs_main, cs); // all valid objects, no votes - for(object_m_cit it = mapObjects.begin(); it != mapObjects.end(); ++it) { - const CGovernanceObject& govobj = it->second; - std::string strHash = it->first.ToString(); + for (const auto& objPair : mapObjects) { + uint256 nHash = objPair.first; + const CGovernanceObject& govobj = objPair.second; + std::string strHash = nHash.ToString(); LogPrint("gobject", "CGovernanceManager::%s -- attempting to sync govobj: %s, peer=%d\n", __func__, strHash, pnode->id); @@ -746,7 +738,7 @@ void CGovernanceManager::SyncAll(CNode* pnode, CConnman& connman) const // Push the inventory budget proposal message over to the other client LogPrint("gobject", "CGovernanceManager::%s -- syncing govobj: %s, peer=%d\n", __func__, strHash, pnode->id); - pnode->PushInventory(CInv(MSG_GOVERNANCE_OBJECT, it->first)); + pnode->PushInventory(CInv(MSG_GOVERNANCE_OBJECT, nHash)); ++nObjCount; } @@ -912,8 +904,8 @@ void CGovernanceManager::CheckMasternodeOrphanVotes(CConnman& connman) ScopedLockBool guard(cs, fRateChecksEnabled, false); - for(object_m_it it = mapObjects.begin(); it != mapObjects.end(); ++it) { - it->second.CheckOrphanVotes(connman); + for (auto& objPair : mapObjects) { + objPair.second.CheckOrphanVotes(connman); } } @@ -1094,22 +1086,25 @@ int CGovernanceManager::RequestGovernanceObjectVotes(const std::vector& if(mapObjects.empty()) return -2; - for(object_m_it it = mapObjects.begin(); it != mapObjects.end(); ++it) { - if(mapAskedRecently.count(it->first)) { - std::map::iterator it1 = mapAskedRecently[it->first].begin(); - while(it1 != mapAskedRecently[it->first].end()) { - if(it1->second < nNow) { - mapAskedRecently[it->first].erase(it1++); + for (const auto& objPair : mapObjects) { + uint256 nHash = objPair.first; + if(mapAskedRecently.count(nHash)) { + auto it = mapAskedRecently[nHash].begin(); + while(it != mapAskedRecently[nHash].end()) { + if(it->second < nNow) { + mapAskedRecently[nHash].erase(it++); } else { - ++it1; + ++it; } } - if(mapAskedRecently[it->first].size() >= nPeersPerHashMax) continue; + if(mapAskedRecently[nHash].size() >= nPeersPerHashMax) continue; } - if(it->second.nObjectType == GOVERNANCE_OBJECT_TRIGGER) { - vpGovObjsTriggersTmp.push_back(&(it->second)); + + auto govObj = objPair.second; + if(govObj.nObjectType == GOVERNANCE_OBJECT_TRIGGER) { + vpGovObjsTriggersTmp.push_back(&govObj); } else { - vpGovObjsTmp.push_back(&(it->second)); + vpGovObjsTmp.push_back(&govObj); } } } @@ -1196,8 +1191,8 @@ void CGovernanceManager::RebuildIndexes() LOCK(cs); cmapVoteToObject.Clear(); - for(object_m_it it = mapObjects.begin(); it != mapObjects.end(); ++it) { - CGovernanceObject& govobj = it->second; + for (auto& objPair : mapObjects) { + CGovernanceObject& govobj = objPair.second; std::vector vecVotes = govobj.GetVoteFile().GetVotes(); for(size_t i = 0; i < vecVotes.size(); ++i) { cmapVoteToObject.Insert(vecVotes[i].GetHash(), &govobj); @@ -1244,10 +1239,8 @@ std::string CGovernanceManager::ToString() const int nTriggerCount = 0; int nOtherCount = 0; - object_m_cit it = mapObjects.begin(); - - while(it != mapObjects.end()) { - switch(it->second.GetObjectType()) { + for (const auto& objPair : mapObjects) { + switch(objPair.second.GetObjectType()) { case GOVERNANCE_OBJECT_PROPOSAL: nProposalCount++; break; @@ -1258,7 +1251,6 @@ std::string CGovernanceManager::ToString() const nOtherCount++; break; } - ++it; } return strprintf("Governance Objects: %d (Proposals: %d, Triggers: %d, Other: %d; Erased: %d), Votes: %d", diff --git a/src/instantx.cpp b/src/instantx.cpp index 1351e01ce607..c508c4429604 100644 --- a/src/instantx.cpp +++ b/src/instantx.cpp @@ -224,12 +224,10 @@ void CInstantSend::Vote(CTxLockCandidate& txLockCandidate, CConnman& connman) if(mapLockRequestAccepted.find(txHash) == mapLockRequestAccepted.end()) return; // check if we need to vote on this candidate's outpoints, // it's possible that we need to vote for several of them - std::map::iterator itOutpointLock = txLockCandidate.mapOutPointLocks.begin(); - while(itOutpointLock != txLockCandidate.mapOutPointLocks.end()) { - - int nPrevoutHeight = GetUTXOHeight(itOutpointLock->first); + for (auto& outpointLockPair : txLockCandidate.mapOutPointLocks) { + int nPrevoutHeight = GetUTXOHeight(outpointLockPair.first); if(nPrevoutHeight == -1) { - LogPrint("instantsend", "CInstantSend::Vote -- Failed to find UTXO %s\n", itOutpointLock->first.ToStringShort()); + LogPrint("instantsend", "CInstantSend::Vote -- Failed to find UTXO %s\n", outpointLockPair.first.ToStringShort()); return; } @@ -239,20 +237,18 @@ void CInstantSend::Vote(CTxLockCandidate& txLockCandidate, CConnman& connman) int nMinRequiredProtocol = std::max(MIN_INSTANTSEND_PROTO_VERSION, mnpayments.GetMinMasternodePaymentsProto()); if(!mnodeman.GetMasternodeRank(activeMasternode.outpoint, nRank, nLockInputHeight, nMinRequiredProtocol)) { LogPrint("instantsend", "CInstantSend::Vote -- Can't calculate rank for masternode %s\n", activeMasternode.outpoint.ToStringShort()); - ++itOutpointLock; continue; } int nSignaturesTotal = COutPointLock::SIGNATURES_TOTAL; if(nRank > nSignaturesTotal) { LogPrint("instantsend", "CInstantSend::Vote -- Masternode not in the top %d (%d)\n", nSignaturesTotal, nRank); - ++itOutpointLock; continue; } LogPrint("instantsend", "CInstantSend::Vote -- In the top %d (%d)\n", nSignaturesTotal, nRank); - std::map >::iterator itVoted = mapVotedOutpoints.find(itOutpointLock->first); + std::map >::iterator itVoted = mapVotedOutpoints.find(outpointLockPair.first); // Check to see if we already voted for this outpoint, // refuse to vote twice or to include the same outpoint in another tx @@ -260,23 +256,22 @@ void CInstantSend::Vote(CTxLockCandidate& txLockCandidate, CConnman& connman) if(itVoted != mapVotedOutpoints.end()) { for (const auto& hash : itVoted->second) { std::map::iterator it2 = mapTxLockCandidates.find(hash); - if(it2->second.HasMasternodeVoted(itOutpointLock->first, activeMasternode.outpoint)) { + if(it2->second.HasMasternodeVoted(outpointLockPair.first, activeMasternode.outpoint)) { // we already voted for this outpoint to be included either in the same tx or in a competing one, // skip it anyway fAlreadyVoted = true; LogPrintf("CInstantSend::Vote -- WARNING: We already voted for this outpoint, skipping: txHash=%s, outpoint=%s\n", - txHash.ToString(), itOutpointLock->first.ToStringShort()); + txHash.ToString(), outpointLockPair.first.ToStringShort()); break; } } } if(fAlreadyVoted) { - ++itOutpointLock; continue; // skip to the next outpoint } // we haven't voted for this outpoint yet, let's try to do this now - CTxLockVote vote(txHash, itOutpointLock->first, activeMasternode.outpoint); + CTxLockVote vote(txHash, outpointLockPair.first, activeMasternode.outpoint); if(!vote.Sign()) { LogPrintf("CInstantSend::Vote -- Failed to sign consensus vote\n"); @@ -290,27 +285,25 @@ void CInstantSend::Vote(CTxLockCandidate& txLockCandidate, CConnman& connman) // vote constructed sucessfully, let's store and relay it uint256 nVoteHash = vote.GetHash(); mapTxLockVotes.insert(std::make_pair(nVoteHash, vote)); - if(itOutpointLock->second.AddVote(vote)) { + if(outpointLockPair.second.AddVote(vote)) { LogPrintf("CInstantSend::Vote -- Vote created successfully, relaying: txHash=%s, outpoint=%s, vote=%s\n", - txHash.ToString(), itOutpointLock->first.ToStringShort(), nVoteHash.ToString()); + txHash.ToString(), outpointLockPair.first.ToStringShort(), nVoteHash.ToString()); if(itVoted == mapVotedOutpoints.end()) { std::set setHashes; setHashes.insert(txHash); - mapVotedOutpoints.insert(std::make_pair(itOutpointLock->first, setHashes)); + mapVotedOutpoints.insert(std::make_pair(outpointLockPair.first, setHashes)); } else { - mapVotedOutpoints[itOutpointLock->first].insert(txHash); - if(mapVotedOutpoints[itOutpointLock->first].size() > 1) { + mapVotedOutpoints[outpointLockPair.first].insert(txHash); + if(mapVotedOutpoints[outpointLockPair.first].size() > 1) { // it's ok to continue, just warn user LogPrintf("CInstantSend::Vote -- WARNING: Vote conflicts with some existing votes: txHash=%s, outpoint=%s, vote=%s\n", - txHash.ToString(), itOutpointLock->first.ToStringShort(), nVoteHash.ToString()); + txHash.ToString(), outpointLockPair.first.ToStringShort(), nVoteHash.ToString()); } } vote.Relay(connman); } - - ++itOutpointLock; } } @@ -549,11 +542,8 @@ void CInstantSend::LockTransactionInputs(const CTxLockCandidate& txLockCandidate if(!txLockCandidate.IsAllOutPointsReady()) return; - std::map::const_iterator it = txLockCandidate.mapOutPointLocks.begin(); - - while(it != txLockCandidate.mapOutPointLocks.end()) { - mapLockedOutpoints.insert(std::make_pair(it->first, txHash)); - ++it; + for (const auto& pair : txLockCandidate.mapOutPointLocks) { + mapLockedOutpoints.insert(std::make_pair(pair.first, txHash)); } LogPrint("instantsend", "CInstantSend::LockTransactionInputs -- done, txid=%s\n", txHash.ToString()); } @@ -649,12 +639,9 @@ int64_t CInstantSend::GetAverageMasternodeOrphanVoteTime() // NOTE: should never actually call this function when mapMasternodeOrphanVotes is empty if(mapMasternodeOrphanVotes.empty()) return 0; - std::map::iterator it = mapMasternodeOrphanVotes.begin(); int64_t total = 0; - - while(it != mapMasternodeOrphanVotes.end()) { - total+= it->second; - ++it; + for (const auto& pair : mapMasternodeOrphanVotes) { + total += pair.second; } return total / mapMasternodeOrphanVotes.size(); @@ -674,11 +661,10 @@ void CInstantSend::CheckAndRemove() uint256 txHash = txLockCandidate.GetHash(); if(txLockCandidate.IsExpired(nCachedBlockHeight)) { LogPrintf("CInstantSend::CheckAndRemove -- Removing expired Transaction Lock Candidate: txid=%s\n", txHash.ToString()); - std::map::iterator itOutpointLock = txLockCandidate.mapOutPointLocks.begin(); - while(itOutpointLock != txLockCandidate.mapOutPointLocks.end()) { - mapLockedOutpoints.erase(itOutpointLock->first); - mapVotedOutpoints.erase(itOutpointLock->first); - ++itOutpointLock; + + for (const auto& pair : txLockCandidate.mapOutPointLocks) { + mapLockedOutpoints.erase(pair.first); + mapVotedOutpoints.erase(pair.first); } mapLockRequestAccepted.erase(txHash); mapLockRequestRejected.erase(txHash); @@ -829,11 +815,9 @@ bool CInstantSend::IsLockedInstantSendTransaction(const uint256& txHash) if(itLockCandidate->second.mapOutPointLocks.empty()) return false; // and all of these outputs must be included in mapLockedOutpoints with correct hash - std::map::iterator itOutpointLock = itLockCandidate->second.mapOutPointLocks.begin(); - while(itOutpointLock != itLockCandidate->second.mapOutPointLocks.end()) { + for (const auto& pair : itLockCandidate->second.mapOutPointLocks) { uint256 hashLocked; - if(!GetLockedOutPointTxHash(itOutpointLock->first, hashLocked) || hashLocked != txHash) return false; - ++itOutpointLock; + if(!GetLockedOutPointTxHash(pair.first, hashLocked) || hashLocked != txHash) return false; } return true; @@ -913,35 +897,28 @@ void CInstantSend::SyncTransaction(const CTransaction& tx, const CBlockIndex *pi txHash.ToString(), nHeightNew); itLockCandidate->second.SetConfirmedHeight(nHeightNew); // Loop through outpoint locks - std::map::iterator itOutpointLock = itLockCandidate->second.mapOutPointLocks.begin(); - while(itOutpointLock != itLockCandidate->second.mapOutPointLocks.end()) { + for (const auto& pair : itLockCandidate->second.mapOutPointLocks) { + // Check corresponding lock votes - std::vector vVotes = itOutpointLock->second.GetVotes(); - std::vector::iterator itVote = vVotes.begin(); - std::map::iterator it; - while(itVote != vVotes.end()) { - uint256 nVoteHash = itVote->GetHash(); + for (const auto& vote : pair.second.GetVotes()) { + uint256 nVoteHash = vote.GetHash(); LogPrint("instantsend", "CInstantSend::SyncTransaction -- txid=%s nHeightNew=%d vote %s updated\n", txHash.ToString(), nHeightNew, nVoteHash.ToString()); - it = mapTxLockVotes.find(nVoteHash); + const auto& it = mapTxLockVotes.find(nVoteHash); if(it != mapTxLockVotes.end()) { it->second.SetConfirmedHeight(nHeightNew); } - ++itVote; } - ++itOutpointLock; } } // check orphan votes - std::map::iterator itOrphanVote = mapTxLockVotesOrphan.begin(); - while(itOrphanVote != mapTxLockVotesOrphan.end()) { - if(itOrphanVote->second.GetTxHash() == txHash) { + for (const auto& pair : mapTxLockVotesOrphan) { + if(pair.second.GetTxHash() == txHash) { LogPrint("instantsend", "CInstantSend::SyncTransaction -- txid=%s nHeightNew=%d vote %s updated\n", - txHash.ToString(), nHeightNew, itOrphanVote->first.ToString()); - mapTxLockVotes[itOrphanVote->first].SetConfirmedHeight(nHeightNew); + txHash.ToString(), nHeightNew, pair.first.ToString()); + mapTxLockVotes[pair.first].SetConfirmedHeight(nHeightNew); } - ++itOrphanVote; } } @@ -1179,10 +1156,8 @@ bool COutPointLock::AddVote(const CTxLockVote& vote) std::vector COutPointLock::GetVotes() const { std::vector vRet; - std::map::const_iterator itVote = mapMasternodeVotes.begin(); - while(itVote != mapMasternodeVotes.end()) { - vRet.push_back(itVote->second); - ++itVote; + for (const auto& pair : mapMasternodeVotes) { + vRet.push_back(pair.second); } return vRet; } @@ -1194,10 +1169,8 @@ bool COutPointLock::HasMasternodeVoted(const COutPoint& outpointMasternodeIn) co void COutPointLock::Relay(CConnman& connman) const { - std::map::const_iterator itVote = mapMasternodeVotes.begin(); - while(itVote != mapMasternodeVotes.end()) { - itVote->second.Relay(connman); - ++itVote; + for (const auto& pair : mapMasternodeVotes) { + pair.second.Relay(connman); } } @@ -1228,10 +1201,8 @@ bool CTxLockCandidate::IsAllOutPointsReady() const { if(mapOutPointLocks.empty()) return false; - std::map::const_iterator it = mapOutPointLocks.begin(); - while(it != mapOutPointLocks.end()) { - if(!it->second.IsReady()) return false; - ++it; + for (const auto& pair : mapOutPointLocks) { + if(!pair.second.IsReady()) return false; } return true; } @@ -1246,10 +1217,8 @@ int CTxLockCandidate::CountVotes() const { // Note: do NOT use vote count to figure out if tx is locked, use IsAllOutPointsReady() instead int nCountVotes = 0; - std::map::const_iterator it = mapOutPointLocks.begin(); - while(it != mapOutPointLocks.end()) { - nCountVotes += it->second.CountVotes(); - ++it; + for (const auto& pair : mapOutPointLocks) { + nCountVotes += pair.second.CountVotes(); } return nCountVotes; } @@ -1268,9 +1237,7 @@ bool CTxLockCandidate::IsTimedOut() const void CTxLockCandidate::Relay(CConnman& connman) const { connman.RelayTransaction(*txLockRequest.tx); - std::map::const_iterator itOutpointLock = mapOutPointLocks.begin(); - while(itOutpointLock != mapOutPointLocks.end()) { - itOutpointLock->second.Relay(connman); - ++itOutpointLock; + for (const auto& pair : mapOutPointLocks) { + pair.second.Relay(connman); } } diff --git a/src/masternode-payments.cpp b/src/masternode-payments.cpp index 58081c4d1baa..858841b4fca1 100644 --- a/src/masternode-payments.cpp +++ b/src/masternode-payments.cpp @@ -1010,12 +1010,11 @@ void CMasternodePayments::RequestLowDataPaymentBlocks(CNode* pnode, CConnman& co pindex = pindex->pprev; } - auto it = mapMasternodeBlocks.begin(); - - while(it != mapMasternodeBlocks.end()) { + for (auto& mnBlockPayees : mapMasternodeBlocks) { + int nBlockHeight = mnBlockPayees.first; int nTotalVotes = 0; bool fFound = false; - for (const auto& payee : it->second.vecPayees) { + for (const auto& payee : mnBlockPayees.second.vecPayees) { if(payee.GetVoteCount() >= MNPAYMENTS_SIGNATURES_REQUIRED) { fFound = true; break; @@ -1026,24 +1025,23 @@ void CMasternodePayments::RequestLowDataPaymentBlocks(CNode* pnode, CConnman& co // or no clear winner was found but there are at least avg number of votes if(fFound || nTotalVotes >= (MNPAYMENTS_SIGNATURES_TOTAL + MNPAYMENTS_SIGNATURES_REQUIRED)/2) { // so just move to the next block - ++it; continue; } // DEBUG DBG ( // Let's see why this failed - for (const auto& payee : it->second.vecPayees) { + for (const auto& payee : mnBlockPayees.second.vecPayees) { CTxDestination address1; ExtractDestination(payee.GetPayee(), address1); CBitcoinAddress address2(address1); printf("payee %s votes %d\n", address2.ToString().c_str(), payee.GetVoteCount()); } - printf("block %d votes total %d\n", it->first, nTotalVotes); + printf("block %d votes total %d\n", nBlockHeight, nTotalVotes); ) // END DEBUG // Low data block found, let's try to sync it uint256 hash; - if(GetBlockHash(hash, it->first)) { + if(GetBlockHash(hash, nBlockHeight)) { vToFetch.push_back(CInv(MSG_MASTERNODE_PAYMENT_BLOCK, hash)); } // We should not violate GETDATA rules @@ -1053,7 +1051,6 @@ void CMasternodePayments::RequestLowDataPaymentBlocks(CNode* pnode, CConnman& co // Start filling new batch vToFetch.clear(); } - ++it; } // Ask for the rest of it if(!vToFetch.empty()) { diff --git a/src/masternodeman.cpp b/src/masternodeman.cpp index e55bcf03d877..9cb94156c330 100644 --- a/src/masternodeman.cpp +++ b/src/masternodeman.cpp @@ -773,14 +773,11 @@ void CMasternodeMan::ProcessPendingMnbRequests(CConnman& connman) bool fDone = connman.ForNode(itPendingMNB->first, [&](CNode* pnode) { // compile request vector std::vector vToFetch; - std::set& setHashes = itPendingMNB->second.second; - std::set::iterator it = setHashes.begin(); - while(it != setHashes.end()) { - if(*it != uint256()) { - vToFetch.push_back(CInv(MSG_MASTERNODE_ANNOUNCE, *it)); - LogPrint("masternode", "-- asking for mnb %s from addr=%s\n", it->ToString(), pnode->addr.ToString()); + for (auto& nHash : itPendingMNB->second.second) { + if(nHash != uint256()) { + vToFetch.push_back(CInv(MSG_MASTERNODE_ANNOUNCE, nHash)); + LogPrint("masternode", "-- asking for mnb %s from addr=%s\n", nHash.ToString(), pnode->addr.ToString()); } - ++it; } // ask for data @@ -1014,20 +1011,18 @@ void CMasternodeMan::DoFullVerificationStep(CConnman& connman) int nRanksTotal = (int)vecMasternodeRanks.size(); // send verify requests only if we are in top MAX_POSE_RANK - rank_pair_vec_t::iterator it = vecMasternodeRanks.begin(); - while(it != vecMasternodeRanks.end()) { - if(it->first > MAX_POSE_RANK) { + for (auto& rankPair : vecMasternodeRanks) { + if(rankPair.first > MAX_POSE_RANK) { LogPrint("masternode", "CMasternodeMan::DoFullVerificationStep -- Must be in top %d to send verify request\n", (int)MAX_POSE_RANK); return; } - if(it->second.outpoint == activeMasternode.outpoint) { - nMyRank = it->first; + if(rankPair.second.outpoint == activeMasternode.outpoint) { + nMyRank = rankPair.first; LogPrint("masternode", "CMasternodeMan::DoFullVerificationStep -- Found self at rank %d/%d, verifying up to %d masternodes\n", nMyRank, nRanksTotal, (int)MAX_POSE_CONNECTIONS); break; } - ++it; } // edge case: list is too short and this masternode is not enabled @@ -1045,7 +1040,7 @@ void CMasternodeMan::DoFullVerificationStep(CConnman& connman) sort(vSortedByAddr.begin(), vSortedByAddr.end(), CompareByAddr()); - it = vecMasternodeRanks.begin() + nOffset; + auto it = vecMasternodeRanks.begin() + nOffset; while(it != vecMasternodeRanks.end()) { if(it->second.IsPoSeVerified() || it->second.IsPoSeBanned()) { LogPrint("masternode", "CMasternodeMan::DoFullVerificationStep -- Already %s%s%s masternode %s address %s, skipping...\n", diff --git a/src/privatesend-client.cpp b/src/privatesend-client.cpp index 4cb33684e473..b88765b0816e 100644 --- a/src/privatesend-client.cpp +++ b/src/privatesend-client.cpp @@ -1343,7 +1343,8 @@ bool CPrivateSendClient::CreateDenominated(const CompactTallyItem& tallyItem, bo do { std::vector vecStandardDenoms = CPrivateSend::GetStandardDenominations(); - BOOST_REVERSE_FOREACH(CAmount nDenomValue, vecStandardDenoms) { + for (auto it = vecStandardDenoms.rbegin(); it != vecStandardDenoms.rend(); ++it) { + CAmount nDenomValue = *it; if(fSkip) { // Note: denoms are skipped if there are already DENOMS_COUNT_MAX of them diff --git a/src/privatesend.cpp b/src/privatesend.cpp index 5f9da4d763b3..04eede421738 100644 --- a/src/privatesend.cpp +++ b/src/privatesend.cpp @@ -418,8 +418,8 @@ int CPrivateSend::GetDenominationsByAmounts(const std::vector& vecAmoun CScript scriptTmp = CScript(); std::vector vecTxOut; - BOOST_REVERSE_FOREACH(CAmount nAmount, vecAmount) { - CTxOut txout(nAmount, scriptTmp); + for (auto it = vecAmount.rbegin(); it != vecAmount.rend(); ++it) { + CTxOut txout((*it), scriptTmp); vecTxOut.push_back(txout); } diff --git a/src/spork.cpp b/src/spork.cpp index 9858b0857ef4..d4fbe64aaa40 100644 --- a/src/spork.cpp +++ b/src/spork.cpp @@ -74,12 +74,8 @@ void CSporkManager::ProcessSpork(CNode* pfrom, const std::string& strCommand, CD ExecuteSpork(spork.nSporkID, spork.nValue); } else if (strCommand == NetMsgType::GETSPORKS) { - - std::map::iterator it = mapSporksActive.begin(); - - while(it != mapSporksActive.end()) { - connman.PushMessage(pfrom, CNetMsgMaker(pfrom->GetSendVersion()).Make(NetMsgType::SPORK, it->second)); - it++; + for (const auto& pair : mapSporksActive) { + connman.PushMessage(pfrom, CNetMsgMaker(pfrom->GetSendVersion()).Make(NetMsgType::SPORK, pair.second)); } } From 0a6c6cda038236f164f42b6ac6a6b6d38977547c Mon Sep 17 00:00:00 2001 From: Nathan Marley Date: Thu, 12 Jul 2018 16:08:22 +0700 Subject: [PATCH 012/282] replace map count/insert w/emplace in instantx.cpp (#2165) * replace map count/insert w/emplace in instantx.cpp This feels like an optimization, something about: ``` if map.count(key) return false else insert(pair) return true ``` ... just feels icky. Plus, `vote.GetMasternodeOutpoint()` is only called once. The previous version might be slightly more readable, however. * use std::pair template constructor shortcut --- src/instantx.cpp | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/src/instantx.cpp b/src/instantx.cpp index c508c4429604..da2d8de31293 100644 --- a/src/instantx.cpp +++ b/src/instantx.cpp @@ -1147,10 +1147,7 @@ bool CTxLockVote::IsFailed() const bool COutPointLock::AddVote(const CTxLockVote& vote) { - if(mapMasternodeVotes.count(vote.GetMasternodeOutpoint())) - return false; - mapMasternodeVotes.insert(std::make_pair(vote.GetMasternodeOutpoint(), vote)); - return true; + return mapMasternodeVotes.emplace(vote.GetMasternodeOutpoint(), vote).second; } std::vector COutPointLock::GetVotes() const From 1a89a7fc7ffab3bfc8e60bdccf04c96129b33a4e Mon Sep 17 00:00:00 2001 From: Nathan Marley Date: Thu, 12 Jul 2018 16:08:43 +0700 Subject: [PATCH 013/282] use nullptr instead of Null This is recommended in modern C++ code as nullptr is more type-safe and can't be converted to an integer, unlike NULL --- src/governance-classes.cpp | 2 +- src/governance-object.cpp | 2 +- src/governance.cpp | 13 ++++++------- src/governance.h | 4 ++-- src/masternode.cpp | 4 ++-- src/masternodeconfig.cpp | 2 +- src/masternodeman.cpp | 18 +++++++++--------- src/privatesend-client.cpp | 2 +- src/rpc/governance.cpp | 6 +++--- 9 files changed, 26 insertions(+), 27 deletions(-) diff --git a/src/governance-classes.cpp b/src/governance-classes.cpp index 23128c21eae7..2dfdccfa934b 100644 --- a/src/governance-classes.cpp +++ b/src/governance-classes.cpp @@ -285,7 +285,7 @@ bool CSuperblockManager::IsSuperblockTriggered(int nBlockHeight) CGovernanceObject* pObj = pSuperblock->GetGovernanceObject(); if(!pObj) { - LogPrintf("CSuperblockManager::IsSuperblockTriggered -- pObj == NULL, continuing\n"); + LogPrintf("CSuperblockManager::IsSuperblockTriggered -- pObj == nullptr, continuing\n"); DBG( std::cout << "IsSuperblockTriggered pObj is NULL, continuing" << std::endl; ); continue; } diff --git a/src/governance-object.cpp b/src/governance-object.cpp index f1f5eca8e2de..fa10f2d5c859 100644 --- a/src/governance-object.cpp +++ b/src/governance-object.cpp @@ -777,7 +777,7 @@ void CGovernanceObject::CheckOrphanVotes(CConnman& connman) continue; } CGovernanceException exception; - if(!ProcessVote(NULL, vote, exception, connman)) { + if(!ProcessVote(nullptr, vote, exception, connman)) { LogPrintf("CGovernanceObject::CheckOrphanVotes -- Failed to add orphan vote: %s\n", exception.what()); } else { diff --git a/src/governance.cpp b/src/governance.cpp index f30251714a29..cee23300062f 100644 --- a/src/governance.cpp +++ b/src/governance.cpp @@ -66,7 +66,7 @@ bool CGovernanceManager::HaveVoteForHash(const uint256& nHash) const { LOCK(cs); - CGovernanceObject* pGovobj = NULL; + CGovernanceObject* pGovobj = nullptr; return cmapVoteToObject.Get(nHash, pGovobj) && pGovobj->GetVoteFile().HasVote(nHash); } @@ -80,8 +80,7 @@ bool CGovernanceManager::SerializeVoteForHash(const uint256& nHash, CDataStream& { LOCK(cs); - CGovernanceObject* pGovobj = NULL; - + CGovernanceObject* pGovobj = nullptr; return cmapVoteToObject.Get(nHash,pGovobj) && pGovobj->GetVoteFile().SerializeVoteToStream(nHash, ss); } @@ -289,7 +288,7 @@ void CGovernanceManager::CheckOrphanVotes(CGovernanceObject& govobj, CGovernance if(pairVote.second < nNow) { fRemove = true; } - else if(govobj.ProcessVote(NULL, vote, exception, connman)) { + else if(govobj.ProcessVote(nullptr, vote, exception, connman)) { vote.Relay(connman); fRemove = true; } @@ -352,7 +351,7 @@ void CGovernanceManager::AddGovernanceObject(CGovernanceObject& govobj, CConnman DBG( std::cout << "CGovernanceManager::AddGovernanceObject After AddNewTrigger" << std::endl; ); } - LogPrintf("CGovernanceManager::AddGovernanceObject -- %s new, received from %s\n", strHash, pfrom? pfrom->GetAddrName() : "NULL"); + LogPrintf("CGovernanceManager::AddGovernanceObject -- %s new, received from %s\n", strHash, pfrom ? pfrom->GetAddrName() : "nullptr"); govobj.Relay(connman); // Update the rate buffer @@ -491,7 +490,7 @@ CGovernanceObject* CGovernanceManager::FindGovernanceObject(const uint256& nHash if(mapObjects.count(nHash)) return &mapObjects[nHash]; - return NULL; + return nullptr; } std::vector CGovernanceManager::GetMatchingVotes(const uint256& nParentHash) const @@ -626,7 +625,7 @@ bool CGovernanceManager::ConfirmInventoryRequest(const CInv& inv) } - hash_s_t* setHash = NULL; + hash_s_t* setHash = nullptr; switch(inv.type) { case MSG_GOVERNANCE_OBJECT: setHash = &setRequestedObjects; diff --git a/src/governance.h b/src/governance.h index 2b5363335ced..57193c4079e9 100644 --- a/src/governance.h +++ b/src/governance.h @@ -308,7 +308,7 @@ class CGovernanceManager std::vector GetCurrentVotes(const uint256& nParentHash, const COutPoint& mnCollateralOutpointFilter) const; std::vector GetAllNewerThan(int64_t nMoreThanTime) const; - void AddGovernanceObject(CGovernanceObject& govobj, CConnman& connman, CNode* pfrom = NULL); + void AddGovernanceObject(CGovernanceObject& govobj, CConnman& connman, CNode* pfrom = nullptr); void UpdateCachesAndClean(); @@ -389,7 +389,7 @@ class CGovernanceManager bool MasternodeRateCheck(const CGovernanceObject& govobj, bool fUpdateFailStatus, bool fForce, bool& fRateCheckBypassed); bool ProcessVoteAndRelay(const CGovernanceVote& vote, CGovernanceException& exception, CConnman& connman) { - bool fOK = ProcessVote(NULL, vote, exception, connman); + bool fOK = ProcessVote(nullptr, vote, exception, connman); if(fOK) { vote.Relay(connman); } diff --git a/src/masternode.cpp b/src/masternode.cpp index a7c9941e4456..4b35ffa39768 100644 --- a/src/masternode.cpp +++ b/src/masternode.cpp @@ -343,7 +343,7 @@ void CMasternode::UpdateLastPaid(const CBlockIndex *pindex, int nMaxBlocksToScan } } - if (BlockReading->pprev == NULL) { assert(BlockReading); break; } + if (BlockReading->pprev == nullptr) { assert(BlockReading); break; } BlockReading = BlockReading->pprev; } @@ -846,7 +846,7 @@ bool CMasternodePing::CheckAndUpdate(CMasternode* pmn, bool fFromNewBroadcast, i return false; } - if (pmn == NULL) { + if (pmn == nullptr) { LogPrint("masternode", "CMasternodePing::CheckAndUpdate -- Couldn't find Masternode entry, masternode=%s\n", masternodeOutpoint.ToStringShort()); return false; } diff --git a/src/masternodeconfig.cpp b/src/masternodeconfig.cpp index 31d4cacc12d4..31182359034e 100644 --- a/src/masternodeconfig.cpp +++ b/src/masternodeconfig.cpp @@ -21,7 +21,7 @@ bool CMasternodeConfig::read(std::string& strErrRet) { if (!streamConfig.good()) { FILE* configFile = fopen(pathMasternodeConfigFile.string().c_str(), "a"); - if (configFile != NULL) { + if (configFile != nullptr) { std::string strHeader = "# Masternode config file\n" "# Format: alias IP:port masternodeprivkey collateral_output_txid collateral_output_index\n" "# Example: mn1 127.0.0.2:18888 43HaYBVUCYjEMeeH1Y4sBGLALQZE1Yc1K64xiqgX37tGBDQL8Xg 2bcd3c84c84f87eaa86e4e56834c92927a07f9e18718810b92e0d0324456a67c 0\n"; diff --git a/src/masternodeman.cpp b/src/masternodeman.cpp index 9cb94156c330..f979805b78d2 100644 --- a/src/masternodeman.cpp +++ b/src/masternodeman.cpp @@ -254,7 +254,7 @@ void CMasternodeMan::CheckAndRemove(CConnman& connman) // mapSeenMasternodeBroadcast.erase(itMnbReplies->first); int nDos; itMnbReplies->second[0].fRecovery = true; - CheckMnbAndUpdateMasternodeList(NULL, itMnbReplies->second[0], nDos, connman); + CheckMnbAndUpdateMasternodeList(nullptr, itMnbReplies->second[0], nDos, connman); } LogPrint("masternode", "CMasternodeMan::CheckAndRemove -- removing mnb recovery reply, masternode=%s, size=%d\n", itMnbReplies->second[0].outpoint.ToStringShort(), (int)itMnbReplies->second.size()); mMnbRecoveryGoodReplies.erase(itMnbReplies++); @@ -446,7 +446,7 @@ CMasternode* CMasternodeMan::Find(const COutPoint &outpoint) { LOCK(cs); auto it = mapMasternodes.find(outpoint); - return it == mapMasternodes.end() ? NULL : &(it->second); + return it == mapMasternodes.end() ? nullptr : &(it->second); } bool CMasternodeMan::Get(const COutPoint& outpoint, CMasternode& masternodeRet) @@ -572,7 +572,7 @@ bool CMasternodeMan::GetNextMasternodeInQueueForPayment(int nBlockHeight, bool f int nTenthNetwork = nMnCount/10; int nCountTenth = 0; arith_uint256 nHighest = 0; - const CMasternode *pBestMasternode = NULL; + const CMasternode *pBestMasternode = nullptr; for (const auto& s : vecMasternodeLastPaid) { arith_uint256 nScore = s.second->CalculateScore(blockHash); if(nScore > nHighest){ @@ -863,7 +863,7 @@ void CMasternodeMan::ProcessMessage(CNode* pfrom, const std::string& strCommand, if(nDos > 0) { // if anything significant failed, mark that node Misbehaving(pfrom->GetId(), nDos); - } else if(pmn != NULL) { + } else if(pmn != nullptr) { // nothing significant failed, mn is a known one too return; } @@ -1082,8 +1082,8 @@ void CMasternodeMan::CheckSameAddr() { LOCK(cs); - CMasternode* pprevMasternode = NULL; - CMasternode* pverifiedMasternode = NULL; + CMasternode* pprevMasternode = nullptr; + CMasternode* pverifiedMasternode = nullptr; for (auto& mnpair : mapMasternodes) { vSortedByAddr.push_back(&mnpair.second); @@ -1097,7 +1097,7 @@ void CMasternodeMan::CheckSameAddr() // initial step if(!pprevMasternode) { pprevMasternode = pmn; - pverifiedMasternode = pmn->IsPoSeVerified() ? pmn : NULL; + pverifiedMasternode = pmn->IsPoSeVerified() ? pmn : nullptr; continue; } // second+ step @@ -1112,7 +1112,7 @@ void CMasternodeMan::CheckSameAddr() pverifiedMasternode = pmn; } } else { - pverifiedMasternode = pmn->IsPoSeVerified() ? pmn : NULL; + pverifiedMasternode = pmn->IsPoSeVerified() ? pmn : nullptr; } pprevMasternode = pmn; } @@ -1277,7 +1277,7 @@ void CMasternodeMan::ProcessVerifyReply(CNode* pnode, CMasternodeVerification& m { LOCK(cs); - CMasternode* prealMasternode = NULL; + CMasternode* prealMasternode = nullptr; std::vector vpMasternodesToBan; uint256 hash1 = mnv.GetSignatureHash1(blockHash); diff --git a/src/privatesend-client.cpp b/src/privatesend-client.cpp index b88765b0816e..2ad6fed2fd67 100644 --- a/src/privatesend-client.cpp +++ b/src/privatesend-client.cpp @@ -487,7 +487,7 @@ bool CPrivateSendClient::CheckPoolStateUpdate(PoolState nStateNew, int nEntriesC // bool CPrivateSendClient::SignFinalTransaction(const CTransaction& finalTransactionNew, CNode* pnode, CConnman& connman) { - if(fMasternodeMode || pnode == NULL) return false; + if(fMasternodeMode || pnode == nullptr) return false; finalMutableTransaction = finalTransactionNew; LogPrintf("CPrivateSendClient::SignFinalTransaction -- finalMutableTransaction=%s", finalMutableTransaction.ToString()); diff --git a/src/rpc/governance.cpp b/src/rpc/governance.cpp index 2940fe4016d7..de05a3f53afe 100644 --- a/src/rpc/governance.cpp +++ b/src/rpc/governance.cpp @@ -718,7 +718,7 @@ UniValue gobject(const JSONRPCRequest& request) // FIND THE GOVERNANCE OBJECT THE USER IS LOOKING FOR CGovernanceObject* pGovObj = governance.FindGovernanceObject(hash); - if(pGovObj == NULL) + if(pGovObj == nullptr) throw JSONRPCError(RPC_INVALID_PARAMETER, "Unknown governance object"); // REPORT BASIC OBJECT STATS @@ -798,7 +798,7 @@ UniValue gobject(const JSONRPCRequest& request) CGovernanceObject* pGovObj = governance.FindGovernanceObject(hash); - if(pGovObj == NULL) { + if(pGovObj == nullptr) { throw JSONRPCError(RPC_INVALID_PARAMETER, "Unknown governance-hash"); } @@ -841,7 +841,7 @@ UniValue gobject(const JSONRPCRequest& request) CGovernanceObject* pGovObj = governance.FindGovernanceObject(hash); - if(pGovObj == NULL) { + if(pGovObj == nullptr) { throw JSONRPCError(RPC_INVALID_PARAMETER, "Unknown governance-hash"); } From 2742ef1540f17b2c4a5d35278f1f44cae36b737d Mon Sep 17 00:00:00 2001 From: Oleg Girko Date: Thu, 12 Jul 2018 10:09:02 +0100 Subject: [PATCH 014/282] depends: Update Qt download url (#2177) --- depends/packages/qt.mk | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/depends/packages/qt.mk b/depends/packages/qt.mk index 3006eebd595d..68f29a4b4b95 100644 --- a/depends/packages/qt.mk +++ b/depends/packages/qt.mk @@ -1,6 +1,6 @@ PACKAGE=qt $(package)_version=5.7.1 -$(package)_download_path=http://download.qt.io/official_releases/qt/5.7/$($(package)_version)/submodules +$(package)_download_path=https://download.qt.io/archive/qt/5.7/$($(package)_version)/submodules $(package)_suffix=opensource-src-$($(package)_version).tar.gz $(package)_file_name=qtbase-$($(package)_suffix) $(package)_sha256_hash=95f83e532d23b3ddbde7973f380ecae1bac13230340557276f75f2e37984e410 From 8f60a8380c0e7e7d81d306a01ec06db8fa96becb Mon Sep 17 00:00:00 2001 From: Alexander Block Date: Thu, 12 Jul 2018 11:17:19 +0200 Subject: [PATCH 015/282] Remove a few annoying debug prints from CMasternodeMan (#2179) These are occurring every second and cause more noise than actual information. --- src/masternodeman.cpp | 4 ---- 1 file changed, 4 deletions(-) diff --git a/src/masternodeman.cpp b/src/masternodeman.cpp index f979805b78d2..cb797558c3c0 100644 --- a/src/masternodeman.cpp +++ b/src/masternodeman.cpp @@ -164,8 +164,6 @@ void CMasternodeMan::Check() { LOCK2(cs_main, cs); - LogPrint("masternode", "CMasternodeMan::Check -- nLastSentinelPingTime=%d, IsSentinelPingActive()=%d\n", nLastSentinelPingTime, IsSentinelPingActive()); - for (auto& mnpair : mapMasternodes) { // NOTE: internally it checks only every MASTERNODE_CHECK_SECONDS seconds // since the last time, so expect some MNs to skip this @@ -796,7 +794,6 @@ void CMasternodeMan::ProcessPendingMnbRequests(CConnman& connman) ++itPendingMNB; } } - LogPrint("masternode", "%s -- mapPendingMNB size: %d\n", __func__, mapPendingMNB.size()); } void CMasternodeMan::ProcessMessage(CNode* pfrom, const std::string& strCommand, CDataStream& vRecv, CConnman& connman) @@ -1171,7 +1168,6 @@ void CMasternodeMan::ProcessPendingMnvRequests(CConnman& connman) ++itPendingMNV; } } - LogPrint("masternode", "%s -- mapPendingMNV size: %d\n", __func__, mapPendingMNV.size()); } void CMasternodeMan::SendVerifyReply(CNode* pnode, CMasternodeVerification& mnv, CConnman& connman) From 8b3b9fd6273c4a2aee8cc00ea3a7d5e1ff3faa6b Mon Sep 17 00:00:00 2001 From: UdjinM6 Date: Mon, 16 Jul 2018 15:47:37 +0300 Subject: [PATCH 016/282] Create ABS related scheduled tasks Replcae scheduled tasks * Fix rare crash when trying to shutdown wallet during mixing Should stop PS and release all keys _before_ wallet is destroyed. * fix nowallet * update doc --- doc/developer-notes.md | 2 -- src/activemasternode.h | 2 ++ src/init.cpp | 30 ++++++++++++++----- src/instantx.h | 2 ++ src/masternode-payments.h | 2 ++ src/masternode-sync.cpp | 2 +- src/masternode-sync.h | 2 ++ src/masternodeman.cpp | 29 +++++++++++++++++++ src/masternodeman.h | 1 + src/netfulfilledman.h | 2 ++ src/privatesend-client.cpp | 34 +++++++--------------- src/privatesend-client.h | 4 +-- src/privatesend-server.cpp | 25 ++++------------ src/privatesend-server.h | 4 +-- src/privatesend.cpp | 59 -------------------------------------- src/privatesend.h | 2 -- 16 files changed, 84 insertions(+), 118 deletions(-) diff --git a/doc/developer-notes.md b/doc/developer-notes.md index e7664a8c3764..d77f4d4813bf 100644 --- a/doc/developer-notes.md +++ b/doc/developer-notes.md @@ -188,8 +188,6 @@ Threads - BitcoinMiner : Generates coins (if wallet is enabled). -- ThreadCheckDarkSendPool : Runs masternode list and sync data update loops - - Shutdown : Does an orderly shutdown of everything. Ignoring IDE/editor files diff --git a/src/activemasternode.h b/src/activemasternode.h index 863c892171c8..30583d524abf 100644 --- a/src/activemasternode.h +++ b/src/activemasternode.h @@ -77,6 +77,8 @@ class CActiveMasternode bool UpdateSentinelPing(int version); + void DoMaintenance(CConnman &connman) { ManageState(connman); } + private: void ManageStateInitial(CConnman& connman); void ManageStateRemote(); diff --git a/src/init.cpp b/src/init.cpp index 17813d18c05d..224b4bb8fc4e 100644 --- a/src/init.cpp +++ b/src/init.cpp @@ -241,8 +241,13 @@ void PrepareShutdown() peerLogic.reset(); g_connman.reset(); - // STORE DATA CACHES INTO SERIALIZED DAT FILES if (!fLiteMode) { +#ifdef ENABLE_WALLET + // Stop PrivateSend, release keys + privateSendClient.fEnablePrivateSend = false; + privateSendClient.ResetPool(); +#endif + // STORE DATA CACHES INTO SERIALIZED DAT FILES CFlatDB flatdb1("mncache.dat", "magicMasternodeCache"); flatdb1.Dump(mnodeman); CFlatDB flatdb2("mnpayments.dat", "magicMasternodePaymentsCache"); @@ -1933,15 +1938,26 @@ bool AppInitMain(boost::thread_group& threadGroup, CScheduler& scheduler) // GetMainSignals().UpdatedBlockTip(chainActive.Tip()); pdsNotificationInterface->InitializeCurrentBlockTip(); - // ********************************************************* Step 11d: start absolute-ps- threads + // ********************************************************* Step 11d: schedule Dash-specific tasks + + if (!fLiteMode) { + scheduler.scheduleEvery(boost::bind(&CNetFulfilledRequestManager::DoMaintenance, boost::ref(netfulfilledman)), 60); + scheduler.scheduleEvery(boost::bind(&CMasternodeSync::DoMaintenance, boost::ref(masternodeSync), boost::ref(*g_connman)), MASTERNODE_SYNC_TICK_SECONDS); + scheduler.scheduleEvery(boost::bind(&CMasternodeMan::DoMaintenance, boost::ref(mnodeman), boost::ref(*g_connman)), 1); + scheduler.scheduleEvery(boost::bind(&CActiveMasternode::DoMaintenance, boost::ref(activeMasternode), boost::ref(*g_connman)), 1); + + scheduler.scheduleEvery(boost::bind(&CMasternodePayments::DoMaintenance, boost::ref(mnpayments)), 60); + scheduler.scheduleEvery(boost::bind(&CGovernanceManager::DoMaintenance, boost::ref(governance), boost::ref(*g_connman)), 60 * 5); - threadGroup.create_thread(boost::bind(&ThreadCheckPrivateSend, boost::ref(*g_connman))); - if (fMasternodeMode) - threadGroup.create_thread(boost::bind(&ThreadCheckPrivateSendServer, boost::ref(*g_connman))); + scheduler.scheduleEvery(boost::bind(&CInstantSend::DoMaintenance, boost::ref(instantsend)), 60); + + if (fMasternodeMode) + scheduler.scheduleEvery(boost::bind(&CPrivateSendServer::DoMaintenance, boost::ref(privateSendServer), boost::ref(*g_connman)), 1); #ifdef ENABLE_WALLET - else - threadGroup.create_thread(boost::bind(&ThreadCheckPrivateSendClient, boost::ref(*g_connman))); + else + scheduler.scheduleEvery(boost::bind(&CPrivateSendClient::DoMaintenance, boost::ref(privateSendClient), boost::ref(*g_connman)), 1); #endif // ENABLE_WALLET + } // ********************************************************* Step 12: start node diff --git a/src/instantx.h b/src/instantx.h index b4885361c595..8281b33b6e46 100644 --- a/src/instantx.h +++ b/src/instantx.h @@ -160,6 +160,8 @@ class CInstantSend void SyncTransaction(const CTransaction& tx, const CBlockIndex *pindex, int posInBlock); std::string ToString() const; + + void DoMaintenance() { CheckAndRemove(); } }; /** diff --git a/src/masternode-payments.h b/src/masternode-payments.h index 640742bca73b..3dc743875934 100644 --- a/src/masternode-payments.h +++ b/src/masternode-payments.h @@ -233,6 +233,8 @@ class CMasternodePayments int GetStorageLimit() const; void UpdatedBlockTip(const CBlockIndex *pindex, CConnman& connman); + + void DoMaintenance() { CheckAndRemove(); } }; #endif diff --git a/src/masternode-sync.cpp b/src/masternode-sync.cpp index 0f16e806d3e9..a81da5d96086 100644 --- a/src/masternode-sync.cpp +++ b/src/masternode-sync.cpp @@ -134,7 +134,7 @@ void CMasternodeSync::ProcessMessage(CNode* pfrom, const std::string& strCommand void CMasternodeSync::ProcessTick(CConnman& connman) { static int nTick = 0; - if(nTick++ % MASTERNODE_SYNC_TICK_SECONDS != 0) return; + nTick++; // reset the sync process if the last call to this function was more than 60 minutes ago (client was in sleep mode) static int64_t nTimeLastProcess = GetTime(); diff --git a/src/masternode-sync.h b/src/masternode-sync.h index d3a63ce7b46b..c1b394cd3c47 100644 --- a/src/masternode-sync.h +++ b/src/masternode-sync.h @@ -78,6 +78,8 @@ class CMasternodeSync void AcceptedBlockHeader(const CBlockIndex *pindexNew); void NotifyHeaderTip(const CBlockIndex *pindexNew, bool fInitialDownload, CConnman& connman); void UpdatedBlockTip(const CBlockIndex *pindexNew, bool fInitialDownload, CConnman& connman); + + void DoMaintenance(CConnman &connman) { ProcessTick(connman); } }; #endif diff --git a/src/masternodeman.cpp b/src/masternodeman.cpp index cb797558c3c0..c1917db8080a 100644 --- a/src/masternodeman.cpp +++ b/src/masternodeman.cpp @@ -7,6 +7,7 @@ #include "addrman.h" #include "alert.h" #include "clientversion.h" +#include "init.h" #include "governance.h" #include "masternode-payments.h" #include "masternode-sync.h" @@ -1758,3 +1759,31 @@ void CMasternodeMan::NotifyMasternodeUpdates(CConnman& connman) fMasternodesAdded = false; fMasternodesRemoved = false; } + +void CMasternodeMan::DoMaintenance(CConnman& connman) +{ + if(fLiteMode) return; // disable all Dash specific functionality + + if(!masternodeSync.IsBlockchainSynced() || ShutdownRequested()) + return; + + static unsigned int nTick = 0; + + nTick++; + + // make sure to check all masternodes first + mnodeman.Check(); + + mnodeman.ProcessPendingMnbRequests(connman); + mnodeman.ProcessPendingMnvRequests(connman); + + if(nTick % 60 == 0) { + mnodeman.ProcessMasternodeConnections(connman); + mnodeman.CheckAndRemove(connman); + mnodeman.WarnMasternodeDaemonUpdates(); + } + + if(fMasternodeMode && (nTick % (60 * 5) == 0)) { + mnodeman.DoFullVerificationStep(connman); + } +} diff --git a/src/masternodeman.h b/src/masternodeman.h index f3afb2460402..3a31cced9997 100644 --- a/src/masternodeman.h +++ b/src/masternodeman.h @@ -245,6 +245,7 @@ class CMasternodeMan */ void NotifyMasternodeUpdates(CConnman& connman); + void DoMaintenance(CConnman &connman); }; #endif diff --git a/src/netfulfilledman.h b/src/netfulfilledman.h index e70d01787fb6..39ec299b1a0a 100644 --- a/src/netfulfilledman.h +++ b/src/netfulfilledman.h @@ -45,6 +45,8 @@ class CNetFulfilledRequestManager void Clear(); std::string ToString() const; + + void DoMaintenance() { CheckAndRemove(); } }; #endif diff --git a/src/privatesend-client.cpp b/src/privatesend-client.cpp index 2ad6fed2fd67..7f1933dcf22e 100644 --- a/src/privatesend-client.cpp +++ b/src/privatesend-client.cpp @@ -1450,34 +1450,22 @@ void CPrivateSendClient::UpdatedBlockTip(const CBlockIndex *pindex) } -//TODO: Rename/move to core -void ThreadCheckPrivateSendClient(CConnman& connman) +void CPrivateSendClient::DoMaintenance(CConnman& connman) { if(fLiteMode) return; // disable all absolute specific functionality if(fMasternodeMode) return; // no client-side mixing on masternodes - static bool fOneThread; - if(fOneThread) return; - fOneThread = true; + if(!masternodeSync.IsBlockchainSynced() || ShutdownRequested()) + return; - // Make this thread recognisable as the PrivateSend thread - RenameThread("absolute-ps-client"); + static unsigned int nTick = 0; + static unsigned int nDoAutoNextRun = nTick + PRIVATESEND_AUTO_TIMEOUT_MIN; - unsigned int nTick = 0; - unsigned int nDoAutoNextRun = nTick + PRIVATESEND_AUTO_TIMEOUT_MIN; - - while (true) - { - MilliSleep(1000); - - if(masternodeSync.IsBlockchainSynced() && !ShutdownRequested()) { - nTick++; - privateSendClient.CheckTimeout(); - privateSendClient.ProcessPendingDsaRequest(connman); - if(nDoAutoNextRun == nTick) { - privateSendClient.DoAutomaticDenominating(connman); - nDoAutoNextRun = nTick + PRIVATESEND_AUTO_TIMEOUT_MIN + GetRandInt(PRIVATESEND_AUTO_TIMEOUT_MAX - PRIVATESEND_AUTO_TIMEOUT_MIN); - } - } + nTick++; + privateSendClient.CheckTimeout(); + privateSendClient.ProcessPendingDsaRequest(connman); + if(nDoAutoNextRun == nTick) { + privateSendClient.DoAutomaticDenominating(connman); + nDoAutoNextRun = nTick + PRIVATESEND_AUTO_TIMEOUT_MIN + GetRandInt(PRIVATESEND_AUTO_TIMEOUT_MAX - PRIVATESEND_AUTO_TIMEOUT_MIN); } } diff --git a/src/privatesend-client.h b/src/privatesend-client.h index 9e6dac2d6bef..afa1f198f2de 100644 --- a/src/privatesend-client.h +++ b/src/privatesend-client.h @@ -191,8 +191,8 @@ class CPrivateSendClient : public CPrivateSendBase void CheckTimeout(); void UpdatedBlockTip(const CBlockIndex *pindex); -}; -void ThreadCheckPrivateSendClient(CConnman& connman); + void DoMaintenance(CConnman& connman); +}; #endif diff --git a/src/privatesend-server.cpp b/src/privatesend-server.cpp index f11301cffb5a..f914dd916130 100644 --- a/src/privatesend-server.cpp +++ b/src/privatesend-server.cpp @@ -891,29 +891,14 @@ void CPrivateSendServer::SetState(PoolState nStateNew) nState = nStateNew; } -//TODO: Rename/move to core -void ThreadCheckPrivateSendServer(CConnman& connman) +void CPrivateSendServer::DoMaintenance(CConnman& connman) { if(fLiteMode) return; // disable all Dash specific functionality if(!fMasternodeMode) return; // only run on masternodes - static bool fOneThread; - if(fOneThread) return; - fOneThread = true; - - // Make this thread recognisable as the PrivateSend thread - RenameThread("absolute-ps-server"); - - unsigned int nTick = 0; - - while (true) - { - MilliSleep(1000); + if(!masternodeSync.IsBlockchainSynced() || ShutdownRequested()) + return; - if(masternodeSync.IsBlockchainSynced() && !ShutdownRequested()) { - nTick++; - privateSendServer.CheckTimeout(connman); - privateSendServer.CheckForCompleteQueue(connman); - } - } + privateSendServer.CheckTimeout(connman); + privateSendServer.CheckForCompleteQueue(connman); } diff --git a/src/privatesend-server.h b/src/privatesend-server.h index aa9909fafca9..ff8af85e6fde 100644 --- a/src/privatesend-server.h +++ b/src/privatesend-server.h @@ -74,8 +74,8 @@ class CPrivateSendServer : public CPrivateSendBase void CheckTimeout(CConnman& connman); void CheckForCompleteQueue(CConnman& connman); -}; -void ThreadCheckPrivateSendServer(CConnman& connman); + void DoMaintenance(CConnman& connman); +}; #endif diff --git a/src/privatesend.cpp b/src/privatesend.cpp index 04eede421738..2292008c4ca9 100644 --- a/src/privatesend.cpp +++ b/src/privatesend.cpp @@ -6,14 +6,10 @@ #include "activemasternode.h" #include "consensus/validation.h" -#include "governance.h" -#include "init.h" -#include "instantx.h" #include "masternode-payments.h" #include "masternode-sync.h" #include "masternodeman.h" #include "messagesigner.h" -#include "netfulfilledman.h" #include "netmessagemaker.h" #include "script/sign.h" #include "txmempool.h" @@ -511,58 +507,3 @@ void CPrivateSend::SyncTransaction(const CTransaction& tx, const CBlockIndex *pi mapDSTX[txHash].SetConfirmedHeight(posInBlock == CMainSignals::SYNC_TRANSACTION_NOT_IN_BLOCK ? -1 : pindex->nHeight); LogPrint("privatesend", "CPrivateSendClient::SyncTransaction -- txid=%s\n", txHash.ToString()); } - -//TODO: Rename/move to core -void ThreadCheckPrivateSend(CConnman& connman) -{ - if(fLiteMode) return; // disable all Absolute specific functionality - - static bool fOneThread; - if(fOneThread) return; - fOneThread = true; - - // Make this thread recognisable as the PrivateSend thread - RenameThread("absolute-ps"); - - unsigned int nTick = 0; - - while (true) - { - MilliSleep(1000); - - // try to sync from all available nodes, one step at a time - masternodeSync.ProcessTick(connman); - - if(masternodeSync.IsBlockchainSynced() && !ShutdownRequested()) { - - nTick++; - - // make sure to check all masternodes first - mnodeman.Check(); - - mnodeman.ProcessPendingMnbRequests(connman); - mnodeman.ProcessPendingMnvRequests(connman); - - // check if we should activate or ping every few minutes, - // slightly postpone first run to give net thread a chance to connect to some peers - if(nTick % MASTERNODE_MIN_MNP_SECONDS == 15) - activeMasternode.ManageState(connman); - - if(nTick % 60 == 0) { - netfulfilledman.CheckAndRemove(); - mnodeman.ProcessMasternodeConnections(connman); - mnodeman.CheckAndRemove(connman); - mnodeman.WarnMasternodeDaemonUpdates(); - mnpayments.CheckAndRemove(); - instantsend.CheckAndRemove(); - } - if(fMasternodeMode && (nTick % (60 * 5) == 0)) { - mnodeman.DoFullVerificationStep(connman); - } - - if(nTick % (60 * 5) == 0) { - governance.DoMaintenance(connman); - } - } - } -} diff --git a/src/privatesend.h b/src/privatesend.h index ef5b135c0a6a..b3ae1409186d 100644 --- a/src/privatesend.h +++ b/src/privatesend.h @@ -438,6 +438,4 @@ class CPrivateSend static void SyncTransaction(const CTransaction& tx, const CBlockIndex *pindex, int posInBlock); }; -void ThreadCheckPrivateSend(CConnman& connman); - #endif From 002f479b198cdf31d2901c47333073ccbcef7cfb Mon Sep 17 00:00:00 2001 From: PaulieD Date: Mon, 16 Jul 2018 07:48:02 -0500 Subject: [PATCH 017/282] Fixes inaccurate round count in CoinControlDialog (#2137) * fixes #2068 * Revert prior and update in correct location --- src/qt/coincontroldialog.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/qt/coincontroldialog.cpp b/src/qt/coincontroldialog.cpp index 003342ca8dd2..34cdfaf3e25d 100644 --- a/src/qt/coincontroldialog.cpp +++ b/src/qt/coincontroldialog.cpp @@ -434,7 +434,7 @@ void CoinControlDialog::viewItemChanged(QTreeWidgetItem* item, int column) item->setCheckState(COLUMN_CHECKBOX, Qt::Unchecked); else { coinControl->Select(outpt); - int nRounds = pwalletMain->GetCappedOutpointPrivateSendRounds(outpt); + int nRounds = pwalletMain->GetRealOutpointPrivateSendRounds(outpt); if (coinControl->fUsePrivateSend && nRounds < privateSendClient.nPrivateSendRounds) { QMessageBox::warning(this, windowTitle(), tr("Non-anonymized input selected. PrivateSend will be disabled.

If you still want to use PrivateSend, please deselect all non-nonymized inputs first and then check PrivateSend checkbox again."), @@ -782,7 +782,7 @@ void CoinControlDialog::updateView() // PrivateSend rounds COutPoint outpoint = COutPoint(out.tx->tx->GetHash(), out.i); - int nRounds = pwalletMain->GetCappedOutpointPrivateSendRounds(outpoint); + int nRounds = pwalletMain->GetRealOutpointPrivateSendRounds(outpoint); if (nRounds >= 0 || fDebug) itemOutput->setText(COLUMN_PRIVATESEND_ROUNDS, QString::number(nRounds)); else itemOutput->setText(COLUMN_PRIVATESEND_ROUNDS, tr("n/a")); From 71a9c86bcf436758384a80becba6f3fd369d524e Mon Sep 17 00:00:00 2001 From: Alexander Block Date: Mon, 16 Jul 2018 14:48:47 +0200 Subject: [PATCH 018/282] Remove deprecated gitian-rpi2.yml descriptor Since backporting Bitcoin 0.14 code, we have the arm-linux-gnueabihf and aarch64-linux-gnu hosts in gitian-linux.yml --- contrib/gitian-descriptors/gitian-rpi2.yml | 112 --------------------- 1 file changed, 112 deletions(-) delete mode 100644 contrib/gitian-descriptors/gitian-rpi2.yml diff --git a/contrib/gitian-descriptors/gitian-rpi2.yml b/contrib/gitian-descriptors/gitian-rpi2.yml deleted file mode 100644 index 20e2fa0a98a7..000000000000 --- a/contrib/gitian-descriptors/gitian-rpi2.yml +++ /dev/null @@ -1,112 +0,0 @@ ---- -name: "absolute-raspberry-0.12" -enable_cache: true -suites: -- "precise" -architectures: -- "amd64" -packages: -- "g++-multilib" -- "git-core" -- "pkg-config" -- "autoconf2.13" -- "libtool" -- "automake" -- "faketime" -- "bsdmainutils" -- "binutils-gold" -reference_datetime: "2017-01-01 00:00:00" -remotes: -- "url": "https://github.com/absolute-community/absolute.git" - "dir": "absolute" -files: -- "raspberrypi-tools.tar.gz" -script: | - WRAP_DIR=$HOME/wrapped - HOSTS="arm-linux-gnueabihf" - CONFIGFLAGS="--enable-upnp-default --enable-glibc-back-compat" - FAKETIME_HOST_PROGS="" - FAKETIME_PROGS="date ar ranlib nm strip" - - tar --warning=no-timestamp -xzf raspberrypi-tools.tar.gz - export TOOLCHAIN_BIN=$(pwd)/raspberrypi-tools/arm-bcm2708/gcc-linaro-arm-linux-gnueabihf-raspbian-x64/bin - export PATH=$PATH:$TOOLCHAIN_BIN - - export QT_RCC_TEST=1 - export GZIP="-9n" - export TAR_OPTIONS="--mtime="$REFERENCE_DATE\\\ $REFERENCE_TIME"" - export TZ="UTC" - export BUILD_DIR=`pwd` - mkdir -p ${WRAP_DIR} - if test -n "$GBUILD_CACHE_ENABLED"; then - export SOURCES_PATH=${GBUILD_COMMON_CACHE} - export BASE_CACHE=${GBUILD_PACKAGE_CACHE} - mkdir -p ${BASE_CACHE} ${SOURCES_PATH} - fi - - # Create global faketime wrappers - for prog in ${FAKETIME_PROGS}; do - echo '#!/bin/bash' > ${WRAP_DIR}/${prog} - echo "REAL=\`which -a ${prog} | grep -v ${WRAP_DIR}/${prog} | head -1\`" >> ${WRAP_DIR}/${prog} - echo 'export LD_PRELOAD=/usr/lib/faketime/libfaketime.so.1' >> ${WRAP_DIR}/${prog} - echo "export FAKETIME=\"${REFERENCE_DATETIME}\"" >> ${WRAP_DIR}/${prog} - echo "\$REAL \$@" >> $WRAP_DIR/${prog} - chmod +x ${WRAP_DIR}/${prog} - done - - # Create per-host faketime wrappers - for i in $HOSTS; do - for prog in ${FAKETIME_HOST_PROGS}; do - echo '#!/bin/bash' > ${WRAP_DIR}/${i}-${prog} - echo "REAL=\`which -a ${i}-${prog} | grep -v ${WRAP_DIR}/${i}-${prog} | head -1\`" >> ${WRAP_DIR}/${i}-${prog} - echo 'export LD_PRELOAD=/usr/lib/faketime/libfaketime.so.1' >> ${WRAP_DIR}/${i}-${prog} - echo "export FAKETIME=\"${REFERENCE_DATETIME}\"" >> ${WRAP_DIR}/${i}-${prog} - echo "\$REAL \$@" >> $WRAP_DIR/${i}-${prog} - chmod +x ${WRAP_DIR}/${i}-${prog} - done - done - export PATH=${WRAP_DIR}:${PATH} - - cd absolute - BASEPREFIX=`pwd`/depends - # Build dependencies for each host - for i in $HOSTS; do - make ${MAKEOPTS} NO_QT=1 -C ${BASEPREFIX} HOST="${i}" - done - - # Create the release tarball using (arbitrarily) the first host - ./autogen.sh - ./configure --prefix=${BASEPREFIX}/`echo "${HOSTS}" | awk '{print $1;}'` - make NO_QT=1 dist - SOURCEDIST=`echo absolutecore-*.tar.gz` - DISTNAME=`echo ${SOURCEDIST} | sed 's/.tar.*//'` - # Correct tar file order - mkdir -p temp - pushd temp - tar xf ../$SOURCEDIST - find absolutecore-* | sort | tar --no-recursion --mode='u+rw,go+r-w,a+X' --owner=0 --group=0 -c -T - | gzip -9n > ../$SOURCEDIST - popd - - ORIGPATH="$PATH" - # Extract the release tarball into a dir for each host and build - for i in ${HOSTS}; do - export PATH=${BASEPREFIX}/${i}/native/bin:${ORIGPATH} - mkdir -p distsrc-${i} - cd distsrc-${i} - INSTALLPATH=`pwd`/installed/${DISTNAME} - mkdir -p ${INSTALLPATH} - tar --strip-components=1 -xf ../$SOURCEDIST - - ./configure --prefix=${BASEPREFIX}/${i} --bindir=${INSTALLPATH}/bin --includedir=${INSTALLPATH}/include --libdir=${INSTALLPATH}/lib --disable-ccache --disable-maintainer-mode --disable-dependency-tracking ${CONFIGFLAGS} - make ${MAKEOPTS} NO_QT=1 - make NO_QT=1 install-strip - cd installed - find . -name "lib*.la" -delete - find . -name "lib*.a" -delete - rm -rf ${DISTNAME}/lib/pkgconfig - find ${DISTNAME} | sort | tar --no-recursion --mode='u+rw,go+r-w,a+X' --owner=0 --group=0 -c -T - | gzip -9n > ${OUTDIR}/${DISTNAME}-${i}.tar.gz - cd ../../ - done - mkdir -p $OUTDIR/src - mv $SOURCEDIST $OUTDIR/src - mv ${OUTDIR}/${DISTNAME}-arm-*.tar.gz ${OUTDIR}/${DISTNAME}-RPi2.tar.gz From 821e60d4313352c16871b4eb2522652d51e601c3 Mon Sep 17 00:00:00 2001 From: Alexander Block Date: Mon, 16 Jul 2018 14:49:23 +0200 Subject: [PATCH 019/282] Install python3 in gitian builds (#2182) We mostly switched to python3, so we should also install it in gitian builds. Especially the osx build needs as it otherwise fails due to missing setuptools. --- contrib/gitian-descriptors/gitian-linux.yml | 1 + contrib/gitian-descriptors/gitian-osx.yml | 4 +++- contrib/gitian-descriptors/gitian-win.yml | 1 + 3 files changed, 5 insertions(+), 1 deletion(-) diff --git a/contrib/gitian-descriptors/gitian-linux.yml b/contrib/gitian-descriptors/gitian-linux.yml index 4a2a66ba3ae7..b624707902de 100755 --- a/contrib/gitian-descriptors/gitian-linux.yml +++ b/contrib/gitian-descriptors/gitian-linux.yml @@ -27,6 +27,7 @@ packages: - "bsdmainutils" - "ca-certificates" - "python" +- "python3" remotes: - "url": "https://github.com/absolute-community/absolute.git" "dir": "absolute" diff --git a/contrib/gitian-descriptors/gitian-osx.yml b/contrib/gitian-descriptors/gitian-osx.yml index 6161d2b1908a..d39c19698737 100644 --- a/contrib/gitian-descriptors/gitian-osx.yml +++ b/contrib/gitian-descriptors/gitian-osx.yml @@ -25,7 +25,9 @@ packages: - "libbz2-dev" - "python" - "python-dev" -- "python-setuptools" +- "python3" +- "python3-dev" +- "python3-setuptools" - "fonts-tuffy" remotes: - "url": "https://github.com/absolute-community/absolute.git" diff --git a/contrib/gitian-descriptors/gitian-win.yml b/contrib/gitian-descriptors/gitian-win.yml index 2eece37e6af5..8cd33c0d56af 100755 --- a/contrib/gitian-descriptors/gitian-win.yml +++ b/contrib/gitian-descriptors/gitian-win.yml @@ -21,6 +21,7 @@ packages: - "zip" - "ca-certificates" - "python" +- "python3" remotes: - "url": "https://github.com/absolute-community/absolute.git" "dir": "absolute" From 2cf1a83ed257968ec5f79f36952851d91b43a3b5 Mon Sep 17 00:00:00 2001 From: gladcow Date: Fri, 20 Jul 2018 16:32:41 +0300 Subject: [PATCH 020/282] Extend Bloom Filter support to InstantSend related messages (#2184) * use bloom filters for IX lock votes * code style fixes --- src/instantx.cpp | 6 +++++- src/net.cpp | 15 +++++++++++++++ src/net.h | 1 + 3 files changed, 21 insertions(+), 1 deletion(-) diff --git a/src/instantx.cpp b/src/instantx.cpp index da2d8de31293..aca5be015cc6 100644 --- a/src/instantx.cpp +++ b/src/instantx.cpp @@ -1122,7 +1122,11 @@ bool CTxLockVote::Sign() void CTxLockVote::Relay(CConnman& connman) const { CInv inv(MSG_TXLOCK_VOTE, GetHash()); - connman.RelayInv(inv); + CTxLockRequest request; + if(instantsend.GetTxLockRequest(txHash, request)) + connman.RelayInvFiltered(inv, *request.tx); + else + connman.RelayInv(inv); } bool CTxLockVote::IsExpired(int nHeight) const diff --git a/src/net.cpp b/src/net.cpp index c63126dd4fa0..6c8257b6dc55 100644 --- a/src/net.cpp +++ b/src/net.cpp @@ -2627,6 +2627,21 @@ void CConnman::RelayInv(CInv &inv, const int minProtoVersion) { pnode->PushInventory(inv); } +void CConnman::RelayInvFiltered(CInv &inv, const CTransaction& relatedTx, const int minProtoVersion) +{ + LOCK(cs_vNodes); + for (const auto& pnode : vNodes) { + if(pnode->nVersion < minProtoVersion) + continue; + { + LOCK(pnode->cs_filter); + if(pnode->pfilter && !pnode->pfilter->IsRelevantAndUpdate(relatedTx)) + continue; + } + pnode->PushInventory(inv); + } +} + void CConnman::RecordBytesRecv(uint64_t bytes) { LOCK(cs_totalBytesRecv); diff --git a/src/net.h b/src/net.h index cd135e5f230d..bc58b4ebac23 100644 --- a/src/net.h +++ b/src/net.h @@ -309,6 +309,7 @@ class CConnman void RelayTransaction(const CTransaction& tx); void RelayTransaction(const CTransaction& tx, const CDataStream& ss); void RelayInv(CInv &inv, const int minProtoVersion = MIN_PEER_PROTO_VERSION); + void RelayInvFiltered(CInv &inv, const CTransaction &relatedTx, const int minProtoVersion = MIN_PEER_PROTO_VERSION); // Addrman functions size_t GetAddressCount() const; From 540cb9daf1c9a3955dce9e0dd978e36acbb0ea2a Mon Sep 17 00:00:00 2001 From: Alexander Block Date: Fri, 20 Jul 2018 15:33:02 +0200 Subject: [PATCH 021/282] Gitian builds with cache in gitian, setup Jenkins * Use subdirectory for depends cache in gitian builds * Make timestamps of wrappers deterministic * Use ccache in gitian builds * Upgrade ccache to latest version (3.4.2) * Build the branch that belongs to the Jenkins build instead of develop --- Jenkinsfile.gitian | 123 ++++++++++++++++++++ contrib/gitian-descriptors/gitian-linux.yml | 35 +++++- contrib/gitian-descriptors/gitian-osx.yml | 26 ++++- contrib/gitian-descriptors/gitian-win.yml | 40 ++++++- depends/packages/native_ccache.mk | 4 +- 5 files changed, 218 insertions(+), 10 deletions(-) create mode 100644 Jenkinsfile.gitian diff --git a/Jenkinsfile.gitian b/Jenkinsfile.gitian new file mode 100644 index 000000000000..87fb1e849e39 --- /dev/null +++ b/Jenkinsfile.gitian @@ -0,0 +1,123 @@ +def targets = [ + 'linux', + 'win', + 'osx', +] + +def osslTarUrl = 'http://downloads.sourceforge.net/project/osslsigncode/osslsigncode/osslsigncode-1.7.1.tar.gz' +def osslPatchUrl = 'https://bitcoincore.org/cfields/osslsigncode-Backports-to-1.7.1.patch' +def SDK_URL='https://bitcoincore.org/depends-sources/sdks' +def OSX_SDK='10.11' +def proc = 4 +def mem = 2000 + +def repositoryUrl = "https://github.com/absolute-community/absolute.git" + +def tasks = [:] +for(int i = 0; i < targets.size(); i++) { + def target = targets[i] + + tasks["${target}"] = { + node { + deleteDir() // cleanup workspace + + def pwd = sh(returnStdout: true, script: 'pwd').trim() + def dockerGid = sh(returnStdout: true, script: "stat -c '%g' /var/run/docker.sock").trim() + def BRANCH_NAME = sh(returnStdout: true, script: 'echo $BRANCH_NAME').trim() + def commit = BRANCH_NAME + def hasCache = false + + def gitianDescriptor + + stage("${target}/prepare") { + dir('absolute') { + checkout scm + gitianDescriptor = readYaml file: "contrib/gitian-descriptors/gitian-${target}.yml" + } + dir('gitian-builder') { + git url: 'https://github.com/absolute-community/gitian-builder.git' + } + sh "mkdir -p absolutecore-binaries" + if (target == "osx") { + dir('gitian-builder') { + sh 'mkdir -p inputs' + sh "curl --location --fail $SDK_URL/MacOSX${OSX_SDK}.sdk.tar.gz -o inputs/MacOSX${OSX_SDK}.sdk.tar.gz" + } + } + + // restore cache + try { + copyArtifacts(projectName: "absolute-gitian-nightly/${BRANCH_NAME}", optional: true, selector: lastSuccessful(), filter: "cache-${gitianDescriptor.name}.tar.gz") + } catch (Exception e) { + } + if (fileExists("cache-${gitianDescriptor.name}.tar.gz")) { + hasCache = true + echo "Using cache from absolute-gitian-nightly/${BRANCH_NAME}" + } else { + try { + copyArtifacts(projectName: 'absolute-gitian-nightly/develop', optional: true, selector: lastSuccessful(), filter: "cache-${gitianDescriptor.name}.tar.gz"); + } catch (Exception e) { + } + if (fileExists("cache-${gitianDescriptor.name}.tar.gz")) { + hasCache = true + echo "Using cache from absolute-gitian-nightly/develop" + } + } + } + + def gitianImage + stage("${target}/builder-image") { + dir('absolute') { + gitianImage = docker.build("absolute-gitian:${env.BUILD_ID}", 'ci -f ci/Dockerfile.gitian-builder') + } + } + + gitianImage.inside("--group-add ${dockerGid} -t -v \"/var/run/docker.sock:/var/run/docker.sock\"") { + sh "mkdir -p gitian-builder/cache" + if (hasCache) { + sh "cd gitian-builder/cache && tar xzfv ../../cache-${gitianDescriptor.name}.tar.gz" + } + + stage("${target}/download") { + dir('gitian-builder') { + sh "mkdir -p inputs" + sh "cd inputs && curl -R -O ${osslPatchUrl}" + sh "cd inputs && curl -R -O ${osslTarUrl}" + sh "make -C ../absolute/depends download SOURCES_PATH=`pwd`/cache/common" + } + } + stage("${target}/base-vm") { + dir('gitian-builder') { + sh "./bin/make-base-vm --suite trusty --arch amd64 --docker" + } + } + + stage("${target}/gbuild") { + dir('gitian-builder') { + // make sure an old version is not running + sh "docker rm -fv gitian-target || true" + + try { + sh """ + tail -F var/install.log & + tail -F var/build.log & + USE_DOCKER=1 ./bin/gbuild -j ${proc} -m ${mem} --commit absolute=${commit} --url absolute=${repositoryUrl} ../absolute/contrib/gitian-descriptors/gitian-${target}.yml + """ + } finally { + // make sure it doesn't run forever + sh "docker rm -fv gitian-target || true" + } + sh "mv build/out/absolutecore-* ../absolutecore-binaries/" + sh "mv build/out/src/absolutecore-* ../absolutehcore-binaries/" + } + archiveArtifacts artifacts: 'absolutecore-binaries/*', fingerprint: true + } + + sh "cd gitian-builder/cache && tar czfv ../../cache-${gitianDescriptor.name}.tar.gz common ${gitianDescriptor.name}" + archiveArtifacts artifacts: "cache-${gitianDescriptor.name}.tar.gz", fingerprint: true + } + } + } +} + +parallel tasks diff --git a/contrib/gitian-descriptors/gitian-linux.yml b/contrib/gitian-descriptors/gitian-linux.yml index b624707902de..e4345db8e593 100755 --- a/contrib/gitian-descriptors/gitian-linux.yml +++ b/contrib/gitian-descriptors/gitian-linux.yml @@ -51,18 +51,37 @@ script: | mkdir -p ${WRAP_DIR} if test -n "$GBUILD_CACHE_ENABLED"; then export SOURCES_PATH=${GBUILD_COMMON_CACHE} - export BASE_CACHE=${GBUILD_PACKAGE_CACHE} + export BASE_CACHE=${GBUILD_PACKAGE_CACHE}/depends mkdir -p ${BASE_CACHE} ${SOURCES_PATH} + + # Setup ccache to use correct cache directories and fix the compiler check of ccache + CONFIGFLAGS="${CONFIGFLAGS} --enable-ccache" + export CCACHE_DIR=${GBUILD_PACKAGE_CACHE}/ccache + # As we later wrap the gcc binaries, this is fast + export CCACHE_COMPILERCHECK="content" + if [ -f ${GBUILD_PACKAGE_CACHE}/ccache.tar.gz ]; then + pushd ${GBUILD_PACKAGE_CACHE} + tar xzf ccache.tar.gz + rm ccache.tar.gz + popd + fi + else + CONFIGFLAGS="${CONFIGFLAGS} --disable-ccache" fi + # We include the GCC version in all wrappers so that ccache can detect compiler upgrades when hashing the wrappers + GCCVERSION=`gcc --version | head -1` + function create_global_faketime_wrappers { for prog in ${FAKETIME_PROGS}; do echo '#!/bin/bash' > ${WRAP_DIR}/${prog} + echo "# GCCVERSION=${GCCVERSION}" >> ${WRAP_DIR}/${prog} echo "REAL=\`which -a ${prog} | grep -v ${WRAP_DIR}/${prog} | head -1\`" >> ${WRAP_DIR}/${prog} echo 'export LD_PRELOAD=/usr/lib/x86_64-linux-gnu/faketime/libfaketime.so.1' >> ${WRAP_DIR}/${prog} echo "export FAKETIME=\"$1\"" >> ${WRAP_DIR}/${prog} echo "\$REAL \$@" >> $WRAP_DIR/${prog} chmod +x ${WRAP_DIR}/${prog} + touch -d "${REFERENCE_DATETIME}" ${WRAP_DIR}/${prog} done } @@ -70,11 +89,13 @@ script: | for i in $HOSTS; do for prog in ${FAKETIME_HOST_PROGS}; do echo '#!/bin/bash' > ${WRAP_DIR}/${i}-${prog} + echo "# GCCVERSION=${GCCVERSION}" >> ${WRAP_DIR}/${i}-${prog} echo "REAL=\`which -a ${i}-${prog} | grep -v ${WRAP_DIR}/${i}-${prog} | head -1\`" >> ${WRAP_DIR}/${i}-${prog} echo 'export LD_PRELOAD=/usr/lib/x86_64-linux-gnu/faketime/libfaketime.so.1' >> ${WRAP_DIR}/${i}-${prog} echo "export FAKETIME=\"$1\"" >> ${WRAP_DIR}/${i}-${prog} echo "\$REAL \$@" >> $WRAP_DIR/${i}-${prog} chmod +x ${WRAP_DIR}/${i}-${prog} + touch -d "${REFERENCE_DATETIME}" ${WRAP_DIR}/${i}-${prog} done done } @@ -99,6 +120,7 @@ script: | rm -f ${WRAP_DIR}/${prog} cat << EOF > ${WRAP_DIR}/${prog} #!/bin/bash + # GCCVERSION=${GCCVERSION} REAL="`which -a ${prog} | grep -v ${WRAP_DIR}/${prog} | head -1`" for var in "\$@" do @@ -111,6 +133,7 @@ script: | \$REAL \$@ EOF chmod +x ${WRAP_DIR}/${prog} + touch -d "${REFERENCE_DATETIME}" ${WRAP_DIR}/${prog} done cd absolute chmod 777 depends/config.sub @@ -155,8 +178,7 @@ script: | mkdir -p ${INSTALLPATH} tar --strip-components=1 -xf ../$SOURCEDIST - CONFIG_SITE=${BASEPREFIX}/${i}/share/config.site ./configure --prefix=/ --disable-ccache --disable-maintainer-mode --disable-dependency-tracking ${CONFIGFLAGS} CFLAGS="${HOST_CFLAGS}" CXXFLAGS="${HOST_CXXFLAGS}" LDFLAGS="${HOST_LDFLAGS}" - chmod 777 share/genbuild.sh + CONFIG_SITE=${BASEPREFIX}/${i}/share/config.site ./configure --prefix=/ --disable-maintainer-mode --disable-dependency-tracking ${CONFIGFLAGS} CFLAGS="${HOST_CFLAGS}" CXXFLAGS="${HOST_CXXFLAGS}" LDFLAGS="${HOST_LDFLAGS}" make ${MAKEOPTS} make ${MAKEOPTS} -C src check-security #TODO: This is a quick hack that disables symbol checking for arm. @@ -183,3 +205,10 @@ script: | mkdir -p $OUTDIR/src mv $SOURCEDIST $OUTDIR/src + # Compress ccache (otherwise the assert file will get too huge) + if [ "$CCACHE_DIR" != "" ]; then + pushd ${GBUILD_PACKAGE_CACHE} + tar czf ccache.tar.gz ccache + rm -rf ccache + popd + fi diff --git a/contrib/gitian-descriptors/gitian-osx.yml b/contrib/gitian-descriptors/gitian-osx.yml index d39c19698737..1ae179fd4ec3 100644 --- a/contrib/gitian-descriptors/gitian-osx.yml +++ b/contrib/gitian-descriptors/gitian-osx.yml @@ -49,8 +49,20 @@ script: | mkdir -p ${WRAP_DIR} if test -n "$GBUILD_CACHE_ENABLED"; then export SOURCES_PATH=${GBUILD_COMMON_CACHE} - export BASE_CACHE=${GBUILD_PACKAGE_CACHE} + export BASE_CACHE=${GBUILD_PACKAGE_CACHE}/depends mkdir -p ${BASE_CACHE} ${SOURCES_PATH} + + # Setup ccache to use correct cache directories + CONFIGFLAGS="${CONFIGFLAGS} --enable-ccache" + export CCACHE_DIR=${GBUILD_PACKAGE_CACHE}/ccache + if [ -f ${GBUILD_PACKAGE_CACHE}/ccache.tar.gz ]; then + pushd ${GBUILD_PACKAGE_CACHE} + tar xzf ccache.tar.gz + rm ccache.tar.gz + popd + fi + else + CONFIGFLAGS="${CONFIGFLAGS} --disable-ccache" fi export ZERO_AR_DATE=1 @@ -63,6 +75,7 @@ script: | echo "export FAKETIME=\"$1\"" >> ${WRAP_DIR}/${prog} echo "\$REAL \$@" >> $WRAP_DIR/${prog} chmod +x ${WRAP_DIR}/${prog} + touch -d "${REFERENCE_DATETIME}" ${WRAP_DIR}/${prog} done } @@ -75,6 +88,7 @@ script: | echo "export FAKETIME=\"$1\"" >> ${WRAP_DIR}/${i}-${prog} echo "\$REAL \$@" >> $WRAP_DIR/${i}-${prog} chmod +x ${WRAP_DIR}/${i}-${prog} + touch -d "${REFERENCE_DATETIME}" ${WRAP_DIR}/${i}-${prog} done done } @@ -124,7 +138,7 @@ script: | mkdir -p ${INSTALLPATH} tar --strip-components=1 -xf ../$SOURCEDIST - CONFIG_SITE=${BASEPREFIX}/${i}/share/config.site ./configure --prefix=/ --disable-ccache --disable-maintainer-mode --disable-dependency-tracking ${CONFIGFLAGS} + CONFIG_SITE=${BASEPREFIX}/${i}/share/config.site ./configure --prefix=/ --disable-maintainer-mode --disable-dependency-tracking ${CONFIGFLAGS} make ${MAKEOPTS} make install-strip DESTDIR=${INSTALLPATH} @@ -156,3 +170,11 @@ script: | mkdir -p $OUTDIR/src mv $SOURCEDIST $OUTDIR/src mv ${OUTDIR}/${DISTNAME}-x86_64-*.tar.gz ${OUTDIR}/${DISTNAME}-osx64.tar.gz + + # Compress ccache (otherwise the assert file will get too huge) + if [ "$CCACHE_DIR" != "" ]; then + pushd ${GBUILD_PACKAGE_CACHE} + tar czf ccache.tar.gz ccache + rm -rf ccache + popd + fi diff --git a/contrib/gitian-descriptors/gitian-win.yml b/contrib/gitian-descriptors/gitian-win.yml index 8cd33c0d56af..7ff889015521 100755 --- a/contrib/gitian-descriptors/gitian-win.yml +++ b/contrib/gitian-descriptors/gitian-win.yml @@ -43,18 +43,37 @@ script: | mkdir -p ${WRAP_DIR} if test -n "$GBUILD_CACHE_ENABLED"; then export SOURCES_PATH=${GBUILD_COMMON_CACHE} - export BASE_CACHE=${GBUILD_PACKAGE_CACHE} + export BASE_CACHE=${GBUILD_PACKAGE_CACHE}/depends mkdir -p ${BASE_CACHE} ${SOURCES_PATH} + + # Setup ccache to use correct cache directories and fix the compiler check of ccache + CONFIGFLAGS="${CONFIGFLAGS} --enable-ccache" + export CCACHE_DIR=${GBUILD_PACKAGE_CACHE}/ccache + # As we later wrap the gcc binaries, this is fast + export CCACHE_COMPILERCHECK="content" + if [ -f ${GBUILD_PACKAGE_CACHE}/ccache.tar.gz ]; then + pushd ${GBUILD_PACKAGE_CACHE} + tar xzf ccache.tar.gz + rm ccache.tar.gz + popd + fi + else + CONFIGFLAGS="${CONFIGFLAGS} --disable-ccache" fi + # We include the GCC version in all wrappers so that ccache can detect compiler upgrades when hashing the wrappers + GCCVERSION=`gcc --version | head -1` + function create_global_faketime_wrappers { for prog in ${FAKETIME_PROGS}; do echo '#!/bin/bash' > ${WRAP_DIR}/${prog} + echo "# GCCVERSION=${GCCVERSION}" >> ${WRAP_DIR}/${prog} echo "REAL=\`which -a ${prog} | grep -v ${WRAP_DIR}/${prog} | head -1\`" >> ${WRAP_DIR}/${prog} echo 'export LD_PRELOAD=/usr/lib/x86_64-linux-gnu/faketime/libfaketime.so.1' >> ${WRAP_DIR}/${prog} echo "export FAKETIME=\"$1\"" >> ${WRAP_DIR}/${prog} echo "\$REAL \$@" >> $WRAP_DIR/${prog} chmod +x ${WRAP_DIR}/${prog} + touch -d "${REFERENCE_DATETIME}" ${WRAP_DIR}/${prog} done } @@ -62,11 +81,13 @@ script: | for i in $HOSTS; do for prog in ${FAKETIME_HOST_PROGS}; do echo '#!/bin/bash' > ${WRAP_DIR}/${i}-${prog} + echo "# GCCVERSION=${GCCVERSION}" >> ${WRAP_DIR}/${i}-${prog} echo "REAL=\`which -a ${i}-${prog} | grep -v ${WRAP_DIR}/${i}-${prog} | head -1\`" >> ${WRAP_DIR}/${i}-${prog} echo 'export LD_PRELOAD=/usr/lib/x86_64-linux-gnu/faketime/libfaketime.so.1' >> ${WRAP_DIR}/${i}-${prog} echo "export FAKETIME=\"$1\"" >> ${WRAP_DIR}/${i}-${prog} echo "\$REAL \$@" >> $WRAP_DIR/${i}-${prog} chmod +x ${WRAP_DIR}/${i}-${prog} + touch -d "${REFERENCE_DATETIME}" ${WRAP_DIR}/${i}-${prog} done done } @@ -78,19 +99,25 @@ script: | mkdir -p ${WRAP_DIR}/${i} for prog in collect2; do echo '#!/bin/bash' > ${WRAP_DIR}/${i}/${prog} + echo "# GCCVERSION=${GCCVERSION}" >> ${WRAP_DIR}/${i}/${prog} REAL=$(${i}-gcc -print-prog-name=${prog}) echo "export MALLOC_PERTURB_=255" >> ${WRAP_DIR}/${i}/${prog} echo "${REAL} \$@" >> $WRAP_DIR/${i}/${prog} chmod +x ${WRAP_DIR}/${i}/${prog} + touch -d "${REFERENCE_DATETIME}" ${WRAP_DIR}/${i}/${prog} done for prog in gcc g++; do echo '#!/bin/bash' > ${WRAP_DIR}/${i}-${prog} + echo "# GCCVERSION=${GCCVERSION}" >> ${WRAP_DIR}/${i}-${prog} echo "REAL=\`which -a ${i}-${prog} | grep -v ${WRAP_DIR}/${i}-${prog} | head -1\`" >> ${WRAP_DIR}/${i}-${prog} + echo '# Add the gcc version to the wrapper so that ccache takes this into account (we use CCACHE_COMPILERCHECK=content)' >> ${WRAP_DIR}/${i}-${prog} + echo "# `${prog} --version | head -1`" >> ${WRAP_DIR}/${i}-${prog} echo 'export LD_PRELOAD=/usr/lib/x86_64-linux-gnu/faketime/libfaketime.so.1' >> ${WRAP_DIR}/${i}-${prog} echo "export FAKETIME=\"$1\"" >> ${WRAP_DIR}/${i}-${prog} echo "export COMPILER_PATH=${WRAP_DIR}/${i}" >> ${WRAP_DIR}/${i}-${prog} echo "\$REAL \$@" >> $WRAP_DIR/${i}-${prog} chmod +x ${WRAP_DIR}/${i}-${prog} + touch -d "${REFERENCE_DATETIME}" ${WRAP_DIR}/${i}-${prog} done done } @@ -144,8 +171,7 @@ script: | mkdir -p ${INSTALLPATH} tar --strip-components=1 -xf ../$SOURCEDIST - CONFIG_SITE=${BASEPREFIX}/${i}/share/config.site ./configure --prefix=/ --disable-ccache --disable-maintainer-mode --disable-dependency-tracking ${CONFIGFLAGS} CFLAGS="${HOST_CFLAGS}" CXXFLAGS="${HOST_CXXFLAGS}" - chmod 777 share/genbuild.sh + CONFIG_SITE=${BASEPREFIX}/${i}/share/config.site ./configure --prefix=/ --disable-maintainer-mode --disable-dependency-tracking ${CONFIGFLAGS} CFLAGS="${HOST_CFLAGS}" CXXFLAGS="${HOST_CXXFLAGS}" make ${MAKEOPTS} make ${MAKEOPTS} -C src check-security make deploy @@ -170,3 +196,11 @@ script: | mv ${OUTDIR}/${DISTNAME}-i686-*-debug.zip ${OUTDIR}/${DISTNAME}-win32-debug.zip mv ${OUTDIR}/${DISTNAME}-x86_64-*.zip ${OUTDIR}/${DISTNAME}-win64.zip mv ${OUTDIR}/${DISTNAME}-i686-*.zip ${OUTDIR}/${DISTNAME}-win32.zip + + # Compress ccache (otherwise the assert file will get too huge) + if [ "$CCACHE_DIR" != "" ]; then + pushd ${GBUILD_PACKAGE_CACHE} + tar czf ccache.tar.gz ccache + rm -rf ccache + popd + fi diff --git a/depends/packages/native_ccache.mk b/depends/packages/native_ccache.mk index 4ed61a49e9ca..3be669dc47cb 100644 --- a/depends/packages/native_ccache.mk +++ b/depends/packages/native_ccache.mk @@ -1,8 +1,8 @@ package=native_ccache -$(package)_version=3.3.3 +$(package)_version=3.4.2 $(package)_download_path=https://samba.org/ftp/ccache $(package)_file_name=ccache-$($(package)_version).tar.bz2 -$(package)_sha256_hash=2985bc5e32ebe38d2958d508eb54ddcad39eed909489c0c2988035214597ca54 +$(package)_sha256_hash=3aa5587793d4c790bd22999bfc678250c029307b3afb9d16f6f4a49c67b78fb3 define $(package)_set_vars $(package)_config_opts= From d367900c71e298606eb0e90674b22327f68a2e36 Mon Sep 17 00:00:00 2001 From: UdjinM6 Date: Wed, 25 Jul 2018 18:09:30 +0300 Subject: [PATCH 022/282] Switch RequestGovernanceObjectVotes from pointers to hashes (#2189) * No need for pointers to gobjects, can simply use hashes in RequestGovernanceObjectVotes * Drop `swap` and `=` in GovernanceObject Were used for shuffling, no longer needed --- src/governance-object.cpp | 24 ----------------------- src/governance-object.h | 8 -------- src/governance.cpp | 40 +++++++++++++++++++-------------------- 3 files changed, 19 insertions(+), 53 deletions(-) diff --git a/src/governance-object.cpp b/src/governance-object.cpp index fa10f2d5c859..c5a6188c4093 100644 --- a/src/governance-object.cpp +++ b/src/governance-object.cpp @@ -735,30 +735,6 @@ void CGovernanceObject::UpdateSentinelVariables() if(GetAbsoluteNoCount(VOTE_SIGNAL_VALID) >= nAbsVoteReq) fCachedValid = false; } -void CGovernanceObject::swap(CGovernanceObject& first, CGovernanceObject& second) // nothrow -{ - // enable ADL (not necessary in our case, but good practice) - using std::swap; - - // by swapping the members of two classes, - // the two classes are effectively swapped - swap(first.nHashParent, second.nHashParent); - swap(first.nRevision, second.nRevision); - swap(first.nTime, second.nTime); - swap(first.nDeletionTime, second.nDeletionTime); - swap(first.nCollateralHash, second.nCollateralHash); - swap(first.vchData, second.vchData); - swap(first.nObjectType, second.nObjectType); - - // swap all cached valid flags - swap(first.fCachedFunding, second.fCachedFunding); - swap(first.fCachedValid, second.fCachedValid); - swap(first.fCachedDelete, second.fCachedDelete); - swap(first.fCachedEndorsed, second.fCachedEndorsed); - swap(first.fDirtyCache, second.fDirtyCache); - swap(first.fExpired, second.fExpired); -} - void CGovernanceObject::CheckOrphanVotes(CConnman& connman) { int64_t nNow = GetAdjustedTime(); diff --git a/src/governance-object.h b/src/governance-object.h index e4a5551b7b1e..2ebfa010c87c 100644 --- a/src/governance-object.h +++ b/src/governance-object.h @@ -195,8 +195,6 @@ class CGovernanceObject CGovernanceObject(const CGovernanceObject& other); - void swap(CGovernanceObject& first, CGovernanceObject& second); // nothrow - // Public Getter methods int64_t GetCreationTime() const { @@ -356,12 +354,6 @@ class CGovernanceObject // AFTER DESERIALIZATION OCCURS, CACHED VARIABLES MUST BE CALCULATED MANUALLY } - CGovernanceObject& operator=(CGovernanceObject from) - { - swap(*this, from); - return *this; - } - private: // FUNCTIONS FOR DEALING WITH DATA STRING void LoadData(); diff --git a/src/governance.cpp b/src/governance.cpp index cee23300062f..95e7627889bc 100644 --- a/src/governance.cpp +++ b/src/governance.cpp @@ -1066,8 +1066,8 @@ int CGovernanceManager::RequestGovernanceObjectVotes(const std::vector& int nTimeout = 60 * 60; size_t nPeersPerHashMax = 3; - std::vector vpGovObjsTmp; - std::vector vpGovObjsTriggersTmp; + std::vector vTriggerObjHashes; + std::vector vOtherObjHashes; // This should help us to get some idea about an impact this can bring once deployed on mainnet. // Testnet is ~40 times smaller in masternode count, but only ~1000 masternodes usually vote, @@ -1099,32 +1099,30 @@ int CGovernanceManager::RequestGovernanceObjectVotes(const std::vector& if(mapAskedRecently[nHash].size() >= nPeersPerHashMax) continue; } - auto govObj = objPair.second; - if(govObj.nObjectType == GOVERNANCE_OBJECT_TRIGGER) { - vpGovObjsTriggersTmp.push_back(&govObj); + if(objPair.second.nObjectType == GOVERNANCE_OBJECT_TRIGGER) { + vTriggerObjHashes.push_back(nHash); } else { - vpGovObjsTmp.push_back(&govObj); + vOtherObjHashes.push_back(nHash); } } } - LogPrint("gobject", "CGovernanceManager::RequestGovernanceObjectVotes -- start: vpGovObjsTriggersTmp %d vpGovObjsTmp %d mapAskedRecently %d\n", - vpGovObjsTriggersTmp.size(), vpGovObjsTmp.size(), mapAskedRecently.size()); + LogPrint("gobject", "CGovernanceManager::RequestGovernanceObjectVotes -- start: vTriggerObjHashes %d vOtherObjHashes %d mapAskedRecently %d\n", + vTriggerObjHashes.size(), vOtherObjHashes.size(), mapAskedRecently.size()); FastRandomContext insecure_rand; - // shuffle pointers - std::random_shuffle(vpGovObjsTriggersTmp.begin(), vpGovObjsTriggersTmp.end(), insecure_rand); - std::random_shuffle(vpGovObjsTmp.begin(), vpGovObjsTmp.end(), insecure_rand); + std::random_shuffle(vTriggerObjHashes.begin(), vTriggerObjHashes.end(), insecure_rand); + std::random_shuffle(vOtherObjHashes.begin(), vOtherObjHashes.end(), insecure_rand); for (int i = 0; i < nMaxObjRequestsPerNode; ++i) { uint256 nHashGovobj; // ask for triggers first - if(vpGovObjsTriggersTmp.size()) { - nHashGovobj = vpGovObjsTriggersTmp.back()->GetHash(); + if(vTriggerObjHashes.size()) { + nHashGovobj = vTriggerObjHashes.back(); } else { - if(vpGovObjsTmp.empty()) break; - nHashGovobj = vpGovObjsTmp.back()->GetHash(); + if(vOtherObjHashes.empty()) break; + nHashGovobj = vOtherObjHashes.back(); } bool fAsked = false; for (const auto& pnode : vNodesCopy) { @@ -1148,17 +1146,17 @@ int CGovernanceManager::RequestGovernanceObjectVotes(const std::vector& if(mapAskedRecently[nHashGovobj].size() >= nPeersPerHashMax) break; } // NOTE: this should match `if` above (the one before `while`) - if(vpGovObjsTriggersTmp.size()) { - vpGovObjsTriggersTmp.pop_back(); + if(vTriggerObjHashes.size()) { + vTriggerObjHashes.pop_back(); } else { - vpGovObjsTmp.pop_back(); + vOtherObjHashes.pop_back(); } if(!fAsked) i--; } - LogPrint("gobject", "CGovernanceManager::RequestGovernanceObjectVotes -- end: vpGovObjsTriggersTmp %d vpGovObjsTmp %d mapAskedRecently %d\n", - vpGovObjsTriggersTmp.size(), vpGovObjsTmp.size(), mapAskedRecently.size()); + LogPrint("gobject", "CGovernanceManager::RequestGovernanceObjectVotes -- end: vTriggerObjHashes %d vOtherObjHashes %d mapAskedRecently %d\n", + vTriggerObjHashes.size(), vOtherObjHashes.size(), mapAskedRecently.size()); - return int(vpGovObjsTriggersTmp.size() + vpGovObjsTmp.size()); + return int(vTriggerObjHashes.size() + vOtherObjHashes.size()); } bool CGovernanceManager::AcceptObjectMessage(const uint256& nHash) From 5004dbf2e20f6575b30dddbce827f47b54f14c8e Mon Sep 17 00:00:00 2001 From: UdjinM6 Date: Wed, 25 Jul 2018 18:09:48 +0300 Subject: [PATCH 023/282] Add helpers GetSentinelString() and GetDaemonString() to CMasternodePing (#2192) --- src/masternode.cpp | 10 ++++++++++ src/masternode.h | 3 +++ src/rpc/masternode.cpp | 12 ++++++------ 3 files changed, 19 insertions(+), 6 deletions(-) diff --git a/src/masternode.cpp b/src/masternode.cpp index 4b35ffa39768..4296b48debd9 100644 --- a/src/masternode.cpp +++ b/src/masternode.cpp @@ -929,6 +929,16 @@ void CMasternodePing::Relay(CConnman& connman) connman.RelayInv(inv); } +std::string CMasternodePing::GetSentinelString() const +{ + return nSentinelVersion > DEFAULT_SENTINEL_VERSION ? SafeIntVersionToString(nSentinelVersion) : "Unknown"; +} + +std::string CMasternodePing::GetDaemonString() const +{ + return nDaemonVersion > DEFAULT_DAEMON_VERSION ? FormatVersion(nDaemonVersion) : "Unknown"; +} + void CMasternode::AddGovernanceVote(uint256 nGovernanceObjectHash) { if(mapGovernanceObjectsVotedOn.count(nGovernanceObjectHash)) { diff --git a/src/masternode.h b/src/masternode.h index 915400bebcca..f2cee704f2fb 100644 --- a/src/masternode.h +++ b/src/masternode.h @@ -103,6 +103,9 @@ class CMasternodePing bool CheckAndUpdate(CMasternode* pmn, bool fFromNewBroadcast, int& nDos, CConnman& connman); void Relay(CConnman& connman); + std::string GetSentinelString() const; + std::string GetDaemonString() const; + explicit operator bool() const; }; diff --git a/src/rpc/masternode.cpp b/src/rpc/masternode.cpp index 3c64d7bd35c8..12c11cf40f2b 100644 --- a/src/rpc/masternode.cpp +++ b/src/rpc/masternode.cpp @@ -558,12 +558,12 @@ UniValue masternodelist(const JSONRPCRequest& request) strOutpoint.find(strFilter) == std::string::npos) continue; obj.push_back(Pair(strOutpoint, strAddress)); } else if (strMode == "daemon") { - std::string strDaemon = mn.lastPing.nDaemonVersion > DEFAULT_DAEMON_VERSION ? FormatVersion(mn.lastPing.nDaemonVersion) : "Unknown"; + std::string strDaemon = mn.lastPing.GetDaemonString(); if (strFilter !="" && strDaemon.find(strFilter) == std::string::npos && strOutpoint.find(strFilter) == std::string::npos) continue; obj.push_back(Pair(strOutpoint, strDaemon)); } else if (strMode == "sentinel") { - std::string strSentinel = mn.lastPing.nSentinelVersion > DEFAULT_SENTINEL_VERSION ? SafeIntVersionToString(mn.lastPing.nSentinelVersion) : "Unknown"; + std::string strSentinel = mn.lastPing.GetSentinelString(); if (strFilter !="" && strSentinel.find(strFilter) == std::string::npos && strOutpoint.find(strFilter) == std::string::npos) continue; obj.push_back(Pair(strOutpoint, strSentinel)); @@ -590,7 +590,7 @@ UniValue masternodelist(const JSONRPCRequest& request) CBitcoinAddress(mn.pubKeyCollateralAddress.GetID()).ToString() << " " << (int64_t)mn.lastPing.sigTime << " " << std::setw(8) << (int64_t)(mn.lastPing.sigTime - mn.sigTime) << " " << - SafeIntVersionToString(mn.lastPing.nSentinelVersion) << " " << + mn.lastPing.GetSentinelString() << " " << (mn.lastPing.fSentinelIsCurrent ? "current" : "expired") << " " << mn.addr.ToString(); std::string strInfo = streamInfo.str(); @@ -604,7 +604,7 @@ UniValue masternodelist(const JSONRPCRequest& request) mn.GetStatus() << " " << mn.nProtocolVersion << " " << mn.lastPing.nDaemonVersion << " " << - SafeIntVersionToString(mn.lastPing.nSentinelVersion) << " " << + mn.lastPing.GetSentinelString() << " " << (mn.lastPing.fSentinelIsCurrent ? "current" : "expired") << " " << (int64_t)mn.lastPing.sigTime << " " << (int64_t)(mn.lastPing.sigTime - mn.sigTime) << " " << @@ -618,8 +618,8 @@ UniValue masternodelist(const JSONRPCRequest& request) objMN.push_back(Pair("payee", CBitcoinAddress(mn.pubKeyCollateralAddress.GetID()).ToString())); objMN.push_back(Pair("status", mn.GetStatus())); objMN.push_back(Pair("protocol", mn.nProtocolVersion)); - objMN.push_back(Pair("daemonversion", mn.lastPing.nDaemonVersion > DEFAULT_DAEMON_VERSION ? FormatVersion(mn.lastPing.nDaemonVersion) : "Unknown")); - objMN.push_back(Pair("sentinelversion", mn.lastPing.nSentinelVersion > DEFAULT_SENTINEL_VERSION ? SafeIntVersionToString(mn.lastPing.nSentinelVersion) : "Unknown")); + objMN.push_back(Pair("daemonversion", mn.lastPing.GetDaemonString())); + objMN.push_back(Pair("sentinelversion", mn.lastPing.GetSentinelString())); objMN.push_back(Pair("sentinelstate", (mn.lastPing.fSentinelIsCurrent ? "current" : "expired"))); objMN.push_back(Pair("lastseen", (int64_t)mn.lastPing.sigTime)); objMN.push_back(Pair("activeseconds", (int64_t)(mn.lastPing.sigTime - mn.sigTime))); From 8ebfb5f54499ee414c5d6f7872149e2b6f2205ab Mon Sep 17 00:00:00 2001 From: UdjinM6 Date: Sat, 28 Jul 2018 16:50:41 +0300 Subject: [PATCH 024/282] Make sure pwalletMain is not null whenever it's used in PS client (#2190) * Make sure pwalletMain is not null whenever it's used in PS client * partially revert --- src/privatesend-client.cpp | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/src/privatesend-client.cpp b/src/privatesend-client.cpp index 7f1933dcf22e..7c0a48018779 100644 --- a/src/privatesend-client.cpp +++ b/src/privatesend-client.cpp @@ -236,6 +236,8 @@ void CPrivateSendClient::SetNull() // void CPrivateSendClient::UnlockCoins() { + if (!pwalletMain) return; + while(true) { TRY_LOCK(pwalletMain->cs_wallet, lockWallet); if(!lockWallet) {MilliSleep(50); continue;} @@ -487,6 +489,8 @@ bool CPrivateSendClient::CheckPoolStateUpdate(PoolState nStateNew, int nEntriesC // bool CPrivateSendClient::SignFinalTransaction(const CTransaction& finalTransactionNew, CNode* pnode, CConnman& connman) { + if (!pwalletMain) return false; + if(fMasternodeMode || pnode == nullptr) return false; finalMutableTransaction = finalTransactionNew; @@ -620,6 +624,13 @@ bool CPrivateSendClient::WaitForAnotherBlock() bool CPrivateSendClient::CheckAutomaticBackup() { + if (!pwalletMain) { + LogPrint("privatesend", "CPrivateSendClient::CheckAutomaticBackup -- Wallet is not initialized, no mixing available.\n"); + strAutoDenomResult = _("Wallet is not initialized") + ", " + _("no mixing available."); + fEnablePrivateSend = false; // no mixing + return false; + } + switch(nWalletBackups) { case 0: LogPrint("privatesend", "CPrivateSendClient::CheckAutomaticBackup -- Automatic backups disabled, no mixing available.\n"); @@ -838,6 +849,8 @@ bool CPrivateSendClient::DoAutomaticDenominating(CConnman& connman, bool fDryRun bool CPrivateSendClient::JoinExistingQueue(CAmount nBalanceNeedsAnonymized, CConnman& connman) { + if (!pwalletMain) return false; + std::vector vecStandardDenoms = CPrivateSend::GetStandardDenominations(); // Look through the queues and see if anything matches for (auto& dsq : vecDarksendQueue) { @@ -918,6 +931,8 @@ bool CPrivateSendClient::JoinExistingQueue(CAmount nBalanceNeedsAnonymized, CCon bool CPrivateSendClient::StartNewQueue(CAmount nValueMin, CAmount nBalanceNeedsAnonymized, CConnman& connman) { + if (!pwalletMain) return false; + int nTries = 0; int nMnCountEnabled = mnodeman.CountEnabled(MIN_PRIVATESEND_PEER_PROTO_VERSION); @@ -1199,6 +1214,8 @@ bool CPrivateSendClient::PrepareDenominate(int nMinRounds, int nMaxRounds, std:: // Create collaterals by looping through inputs grouped by addresses bool CPrivateSendClient::MakeCollateralAmounts(CConnman& connman) { + if (!pwalletMain) return false; + std::vector vecTally; if(!pwalletMain->SelectCoinsGrouppedByAddresses(vecTally, false)) { LogPrint("privatesend", "CPrivateSendClient::MakeCollateralAmounts -- SelectCoinsGrouppedByAddresses can't find any inputs!\n"); @@ -1225,6 +1242,8 @@ bool CPrivateSendClient::MakeCollateralAmounts(CConnman& connman) // Split up large inputs or create fee sized inputs bool CPrivateSendClient::MakeCollateralAmounts(const CompactTallyItem& tallyItem, bool fTryDenominated, CConnman& connman) { + if (!pwalletMain) return false; + LOCK2(cs_main, pwalletMain->cs_wallet); // denominated input is always a single one, so we can check its amount directly and return early @@ -1297,6 +1316,8 @@ bool CPrivateSendClient::MakeCollateralAmounts(const CompactTallyItem& tallyItem // Create denominations by looping through inputs grouped by addresses bool CPrivateSendClient::CreateDenominated(CConnman& connman) { + if (!pwalletMain) return false; + LOCK2(cs_main, pwalletMain->cs_wallet); std::vector vecTally; @@ -1319,6 +1340,8 @@ bool CPrivateSendClient::CreateDenominated(CConnman& connman) // Create denominations bool CPrivateSendClient::CreateDenominated(const CompactTallyItem& tallyItem, bool fCreateMixingCollaterals, CConnman& connman) { + if (!pwalletMain) return false; + std::vector vecSend; CKeyHolderStorage keyHolderStorageDenom; From 3b4c716ea7e327037ff5c772f970c4ed81375f29 Mon Sep 17 00:00:00 2001 From: UdjinM6 Date: Sat, 28 Jul 2018 16:50:58 +0300 Subject: [PATCH 025/282] Show some info about the wallet dumped via dumpwallet (#2191) Also show a warning that the file must be kept secure. --- src/wallet/rpcdump.cpp | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/src/wallet/rpcdump.cpp b/src/wallet/rpcdump.cpp index 5cda88e0de3c..04050394939f 100644 --- a/src/wallet/rpcdump.cpp +++ b/src/wallet/rpcdump.cpp @@ -778,6 +778,12 @@ UniValue dumpwallet(const JSONRPCRequest& request) file << strprintf("# mined on %s\n", EncodeDumpTime(chainActive.Tip()->GetBlockTime())); file << "\n"; + UniValue obj(UniValue::VOBJ); + obj.push_back(Pair("dashcoreversion", CLIENT_BUILD)); + obj.push_back(Pair("lastblockheight", chainActive.Height())); + obj.push_back(Pair("lastblockhash", chainActive.Tip()->GetBlockHash().ToString())); + obj.push_back(Pair("lastblocktime", EncodeDumpTime(chainActive.Tip()->GetBlockTime()))); + // add the base58check encoded extended master if the wallet uses HD CHDChain hdChainCurrent; if (pwalletMain->GetHDChain(hdChainCurrent)) @@ -820,6 +826,7 @@ UniValue dumpwallet(const JSONRPCRequest& request) file << "# WARNING: ACCOUNT " << i << " IS MISSING!" << "\n\n"; } } + obj.push_back(Pair("hdaccounts", int(hdChainCurrent.CountAccounts()))); } for (std::vector >::const_iterator it = vKeyBirth.begin(); it != vKeyBirth.end(); it++) { @@ -842,7 +849,13 @@ UniValue dumpwallet(const JSONRPCRequest& request) file << "\n"; file << "# End of dump\n"; file.close(); - return NullUniValue; + + std::string strWarning = strprintf(_("%s file contains all private keys from this wallet. Do not share it with anyone!"), request.params[0].get_str().c_str()); + obj.push_back(Pair("keys", int(vKeyBirth.size()))); + obj.push_back(Pair("file", request.params[0].get_str().c_str())); + obj.push_back(Pair("warning", strWarning)); + + return obj; } From 40830143d83ba8edcbf6ec093e3bbf7d491a5f67 Mon Sep 17 00:00:00 2001 From: UdjinM6 Date: Sat, 28 Jul 2018 16:51:13 +0300 Subject: [PATCH 026/282] Fix active masternode task schedule (#2193) --- src/init.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/init.cpp b/src/init.cpp index 224b4bb8fc4e..d299e0478f38 100644 --- a/src/init.cpp +++ b/src/init.cpp @@ -1944,7 +1944,7 @@ bool AppInitMain(boost::thread_group& threadGroup, CScheduler& scheduler) scheduler.scheduleEvery(boost::bind(&CNetFulfilledRequestManager::DoMaintenance, boost::ref(netfulfilledman)), 60); scheduler.scheduleEvery(boost::bind(&CMasternodeSync::DoMaintenance, boost::ref(masternodeSync), boost::ref(*g_connman)), MASTERNODE_SYNC_TICK_SECONDS); scheduler.scheduleEvery(boost::bind(&CMasternodeMan::DoMaintenance, boost::ref(mnodeman), boost::ref(*g_connman)), 1); - scheduler.scheduleEvery(boost::bind(&CActiveMasternode::DoMaintenance, boost::ref(activeMasternode), boost::ref(*g_connman)), 1); + scheduler.scheduleEvery(boost::bind(&CActiveMasternode::DoMaintenance, boost::ref(activeMasternode), boost::ref(*g_connman)), MASTERNODE_MIN_MNP_SECONDS); scheduler.scheduleEvery(boost::bind(&CMasternodePayments::DoMaintenance, boost::ref(mnpayments)), 60); scheduler.scheduleEvery(boost::bind(&CGovernanceManager::DoMaintenance, boost::ref(governance), boost::ref(*g_connman)), 60 * 5); From dd7acee4cd88251dcb5cb08f9dc1127b3c031248 Mon Sep 17 00:00:00 2001 From: UdjinM6 Date: Sat, 28 Jul 2018 16:51:29 +0300 Subject: [PATCH 027/282] Move block template specific stuff from CBlock to CBlockTemplate (#2195) --- src/miner.cpp | 4 ++-- src/miner.h | 2 ++ src/primitives/block.h | 4 ---- src/rpc/mining.cpp | 12 ++++++------ 4 files changed, 10 insertions(+), 12 deletions(-) diff --git a/src/miner.cpp b/src/miner.cpp index 2272e1a94d48..41df3fca61cd 100644 --- a/src/miner.cpp +++ b/src/miner.cpp @@ -172,9 +172,9 @@ std::unique_ptr BlockAssembler::CreateNewBlock(const CScript& sc // Update coinbase transaction with additional info about masternode and governance payments, // get some info back to pass to getblocktemplate - FillBlockPayments(coinbaseTx, nHeight, blockReward, pblock->txoutMasternode, pblock->voutSuperblock); + FillBlockPayments(coinbaseTx, nHeight, blockReward, pblocktemplate->txoutMasternode, pblocktemplate->voutSuperblock); // LogPrintf("CreateNewBlock -- nBlockHeight %d blockReward %lld txoutMasternode %s coinbaseTx %s", - // nHeight, blockReward, pblock->txoutMasternode.ToString(), coinbaseTx.ToString()); + // nHeight, blockReward, pblocktemplate->txoutMasternode.ToString(), coinbaseTx.ToString()); pblock->vtx[0] = MakeTransactionRef(std::move(coinbaseTx)); pblocktemplate->vTxFees[0] = -nFees; diff --git a/src/miner.h b/src/miner.h index de46fe2c7c9b..7a46f18f1303 100644 --- a/src/miner.h +++ b/src/miner.h @@ -30,6 +30,8 @@ struct CBlockTemplate CBlock block; std::vector vTxFees; std::vector vTxSigOps; + CTxOut txoutMasternode; // masternode payment + std::vector voutSuperblock; // superblock payment }; // Container for tracking updates to ancestor feerate as we include (parent) diff --git a/src/primitives/block.h b/src/primitives/block.h index adfccf10ebf1..772cbab5c1ea 100644 --- a/src/primitives/block.h +++ b/src/primitives/block.h @@ -79,8 +79,6 @@ class CBlock : public CBlockHeader std::vector vtx; // memory only - mutable CTxOut txoutMasternode; // masternode payment - mutable std::vector voutSuperblock; // superblock payment mutable bool fChecked; CBlock() @@ -106,8 +104,6 @@ class CBlock : public CBlockHeader { CBlockHeader::SetNull(); vtx.clear(); - txoutMasternode = CTxOut(); - voutSuperblock.clear(); fChecked = false; } diff --git a/src/rpc/mining.cpp b/src/rpc/mining.cpp index 340fe95cc8bd..e7acf9960bc2 100644 --- a/src/rpc/mining.cpp +++ b/src/rpc/mining.cpp @@ -702,21 +702,21 @@ UniValue getblocktemplate(const JSONRPCRequest& request) result.push_back(Pair("height", (int64_t)(pindexPrev->nHeight+1))); UniValue masternodeObj(UniValue::VOBJ); - if(pblock->txoutMasternode != CTxOut()) { + if(pblocktemplate->txoutMasternode != CTxOut()) { CTxDestination address1; - ExtractDestination(pblock->txoutMasternode.scriptPubKey, address1); + ExtractDestination(pblocktemplate->txoutMasternode.scriptPubKey, address1); CBitcoinAddress address2(address1); masternodeObj.push_back(Pair("payee", address2.ToString().c_str())); - masternodeObj.push_back(Pair("script", HexStr(pblock->txoutMasternode.scriptPubKey))); - masternodeObj.push_back(Pair("amount", pblock->txoutMasternode.nValue)); + masternodeObj.push_back(Pair("script", HexStr(pblocktemplate->txoutMasternode.scriptPubKey))); + masternodeObj.push_back(Pair("amount", pblocktemplate->txoutMasternode.nValue)); } result.push_back(Pair("masternode", masternodeObj)); result.push_back(Pair("masternode_payments_started", pindexPrev->nHeight + 1 > consensusParams.nMasternodePaymentsStartBlock)); result.push_back(Pair("masternode_payments_enforced", sporkManager.IsSporkActive(SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT))); UniValue superblockObjArray(UniValue::VARR); - if(pblock->voutSuperblock.size()) { - for (const auto& txout : pblock->voutSuperblock) { + if(pblocktemplate->voutSuperblock.size()) { + for (const auto& txout : pblocktemplate->voutSuperblock) { UniValue entry(UniValue::VOBJ); CTxDestination address1; ExtractDestination(txout.scriptPubKey, address1); From 431545cff7092ac10cf4739048d4fb7cc96a3bee Mon Sep 17 00:00:00 2001 From: UdjinM6 Date: Sat, 28 Jul 2018 16:51:45 +0300 Subject: [PATCH 028/282] Fix wallet lock check in DoAutomaticDenominating (#2196) --- src/privatesend-client.cpp | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/src/privatesend-client.cpp b/src/privatesend-client.cpp index 7c0a48018779..6c1792f82ef7 100644 --- a/src/privatesend-client.cpp +++ b/src/privatesend-client.cpp @@ -701,7 +701,6 @@ bool CPrivateSendClient::DoAutomaticDenominating(CConnman& connman, bool fDryRun { if(fMasternodeMode) return false; // no client-side mixing on masternodes if(!fEnablePrivateSend) return false; - if(!pwalletMain || pwalletMain->IsLocked(true)) return false; if(nState != POOL_STATE_IDLE) return false; if(!masternodeSync.IsMasternodeListSynced()) { @@ -709,6 +708,16 @@ bool CPrivateSendClient::DoAutomaticDenominating(CConnman& connman, bool fDryRun return false; } + if (!pwalletMain) { + strAutoDenomResult = _("Wallet is not initialized"); + return false; + } + + if(!fDryRun && pwalletMain->IsLocked(true)) { + strAutoDenomResult = _("Wallet is locked."); + return false; + } + if(!CheckAutomaticBackup()) return false; @@ -723,11 +732,6 @@ bool CPrivateSendClient::DoAutomaticDenominating(CConnman& connman, bool fDryRun return false; } - if(!fDryRun && pwalletMain->IsLocked(true)) { - strAutoDenomResult = _("Wallet is locked."); - return false; - } - if(WaitForAnotherBlock()) { LogPrintf("CPrivateSendClient::DoAutomaticDenominating -- Last successful PrivateSend action was too recent\n"); strAutoDenomResult = _("Last successful PrivateSend action was too recent."); From 05954119f79855b36c6991396d0f399818e1ba3c Mon Sep 17 00:00:00 2001 From: gladcow Date: Sat, 28 Jul 2018 19:39:37 +0300 Subject: [PATCH 029/282] Remove dummy confirmations in RPC API and GUI for InstantSend * remove instandsenddepth option * remove CInstantSend::GetConfirmations * Explicit IXlocks processing in the code using GetDepthInMainChain * remove dummy confirmations for IX locks * remove unused constant * Track IS status in TransactionStatus * Highlight IS in tx list * Customize confirmation icons for IS txes * Fix issues: - bring back removed comment; - simplify 2 complex condition to ose `IsTrusted()` function only; - rename `IsLockedIX` function to 'IsLockedByInstantSend`; * Revert condition with IsTrusted() * code style fix * remove dummy confirmations from instantsend.md * fix instantsend.md --- doc/instantsend.md | 54 +----------------- src/governance-object.cpp | 5 +- src/init.cpp | 4 -- src/instantx.cpp | 6 -- src/instantx.h | 10 ---- src/qt/guiconstants.h | 2 + src/qt/transactionrecord.cpp | 1 + src/qt/transactionrecord.h | 2 + src/qt/transactiontablemodel.cpp | 34 +++++++++-- src/qt/walletmodel.cpp | 2 +- src/wallet/rpcwallet.cpp | 96 ++++++++++++++++---------------- src/wallet/wallet.cpp | 38 +++++++------ src/wallet/wallet.h | 9 +-- 13 files changed, 113 insertions(+), 150 deletions(-) diff --git a/doc/instantsend.md b/doc/instantsend.md index 70b5df824fdd..18f1e6c8adb0 100644 --- a/doc/instantsend.md +++ b/doc/instantsend.md @@ -25,56 +25,4 @@ When a wallet InstantSend transaction is successfully locked a shell command pro #### RPC -Details pertaining to an observed "Transaction Lock" can also be retrieved through RPC, it’s important however to understand the underlying mechanism. - -By default, the Absolute Core daemon will launch using the following constant: - -``` -static const int DEFAULT_INSTANTSEND_DEPTH = 5; -``` - -This value can be overridden by passing the following argument to the Absolute Core daemon: - -``` --instantsenddepth= -``` - -The key thing to understand is that this value indicates the number of "confirmations" a successful Transaction Lock represents. When Wallet RPC commands which support `minconf` and `addlockconf` parameters (such as `listreceivedbyaddress`) are performed and `addlockconf` is `true`, then `instantsenddepth` attribute is taken into account when returning information about the transaction. In this case the value in `confirmations` field you see through RPC is showing the number of `"Blockchain Confirmations" + "InstantSend Depth"` (assuming the funds were sent via InstantSend). - -There is also a field named `instantlock` (that is present in commands such as `listsinceblock`). The value in this field indicates whether a given transaction is locked via InstantSend. - -**Examples** - -1. `listreceivedbyaddress 0 true` - * InstantSend transaction just occurred: - * confirmations: 5 - * InstantSend transaction received one confirmation from blockchain: - * confirmations: 6 - * non-InstantSend transaction just occurred: - * confirmations: 0 - * non-InstantSend transaction received one confirmation from blockchain: - * confirmations: 1 - -2. `listreceivedbyaddress 0` - * InstantSend transaction just occurred: - * confirmations: 0 - * InstantSend transaction received one confirmation from blockchain: - * confirmations: 1 - * non-InstantSend transaction just occurred: - * confirmations: 0 - * non-InstantSend transaction received one confirmation from blockchain: - * confirmations: 1 - -3. `listsinceblock` - * InstantSend transaction just occurred: - * confirmations: 0 - * instantlock: true - * InstantSend transaction received one confirmation from blockchain: - * confirmations: 1 - * instantlock: true - * non-InstantSend transaction just occurred: - * confirmations: 0 - * instantlock: false - * non-InstantSend transaction received one confirmation from blockchain: - * confirmations: 1 - * instantlock: false +Details pertaining to an observed "Transaction Lock" can also be retrieved through RPC. There is a boolean field named `instantlock` which indicates whether a given transaction is locked via InstantSend. This field is present in the output of some wallet RPC commands e.g. `listsinceblock`, `gettransaction` etc. as well as in the output of some mempool RPC commands e.g. `getmempoolentry` and a couple of others like `getrawmempool` (for `verbose=true` only). diff --git a/src/governance-object.cpp b/src/governance-object.cpp index c5a6188c4093..4cf8db157fef 100644 --- a/src/governance-object.cpp +++ b/src/governance-object.cpp @@ -605,7 +605,7 @@ bool CGovernanceObject::IsCollateralValid(std::string& strError, bool& fMissingC // GET CONFIRMATIONS FOR TRANSACTION AssertLockHeld(cs_main); - int nConfirmationsIn = instantsend.GetConfirmations(nCollateralHash); + int nConfirmationsIn = 0; if (nBlockHash != uint256()) { BlockMap::iterator mi = mapBlockIndex.find(nBlockHash); if (mi != mapBlockIndex.end() && (*mi).second) { @@ -616,7 +616,8 @@ bool CGovernanceObject::IsCollateralValid(std::string& strError, bool& fMissingC } } - if(nConfirmationsIn < GOVERNANCE_FEE_CONFIRMATIONS) { + if((nConfirmationsIn < GOVERNANCE_FEE_CONFIRMATIONS) && + (!instantsend.IsLockedInstantSendTransaction(nCollateralHash))){ strError = strprintf("Collateral requires at least %d confirmations to be relayed throughout the network (it has only %d)", GOVERNANCE_FEE_CONFIRMATIONS, nConfirmationsIn); if (nConfirmationsIn >= GOVERNANCE_MIN_RELAY_FEE_CONFIRMATIONS) { fMissingConfirmations = true; diff --git a/src/init.cpp b/src/init.cpp index d299e0478f38..a3c459eb4b51 100644 --- a/src/init.cpp +++ b/src/init.cpp @@ -575,7 +575,6 @@ std::string HelpMessage(HelpMessageMode mode) strUsage += HelpMessageGroup(_("InstantSend options:")); strUsage += HelpMessageOpt("-enableinstantsend=", strprintf(_("Enable InstantSend, show confirmations for locked transactions (0-1, default: %u)"), 1)); - strUsage += HelpMessageOpt("-instantsenddepth=", strprintf(_("Show N confirmations for a successfully locked transaction (%u-%u, default: %u)"), MIN_INSTANTSEND_DEPTH, MAX_INSTANTSEND_DEPTH, DEFAULT_INSTANTSEND_DEPTH)); strUsage += HelpMessageOpt("-instantsendnotify=", _("Execute command when a wallet InstantSend transaction is successfully locked (%s in cmd is replaced by TxID)")); @@ -1865,11 +1864,8 @@ bool AppInitMain(boost::thread_group& threadGroup, CScheduler& scheduler) #endif // ENABLE_WALLET fEnableInstantSend = GetBoolArg("-enableinstantsend", 1); - nInstantSendDepth = GetArg("-instantsenddepth", DEFAULT_INSTANTSEND_DEPTH); - nInstantSendDepth = std::min(std::max(nInstantSendDepth, MIN_INSTANTSEND_DEPTH), MAX_INSTANTSEND_DEPTH); LogPrintf("fLiteMode %d\n", fLiteMode); - LogPrintf("nInstantSendDepth %d\n", nInstantSendDepth); #ifdef ENABLE_WALLET LogPrintf("PrivateSend liquidityprovider: %d\n", privateSendClient.nLiquidityProvider); LogPrintf("PrivateSend rounds: %d\n", privateSendClient.nPrivateSendRounds); diff --git a/src/instantx.cpp b/src/instantx.cpp index aca5be015cc6..a82f45993e5e 100644 --- a/src/instantx.cpp +++ b/src/instantx.cpp @@ -34,7 +34,6 @@ extern CWallet* pwalletMain; extern CTxMemPool mempool; bool fEnableInstantSend = true; -int nInstantSendDepth = DEFAULT_INSTANTSEND_DEPTH; int nCompleteTXLocks; CInstantSend instantsend; @@ -839,11 +838,6 @@ int CInstantSend::GetTransactionLockSignatures(const uint256& txHash) return -1; } -int CInstantSend::GetConfirmations(const uint256 &nTXHash) -{ - return IsLockedInstantSendTransaction(nTXHash) ? nInstantSendDepth : 0; -} - bool CInstantSend::IsTxLockCandidateTimedOut(const uint256& txHash) { if(!fEnableInstantSend) return false; diff --git a/src/instantx.h b/src/instantx.h index 8281b33b6e46..129e50029cef 100644 --- a/src/instantx.h +++ b/src/instantx.h @@ -27,14 +27,6 @@ extern CInstantSend instantsend; (1000/2900.0)**5 = 0.004875397277841433 */ -// The INSTANTSEND_DEPTH is the "pseudo block depth" level assigned to locked -// txs to indicate the degree of confidence in their eventual confirmation and -// inability to be double-spent (adjustable via command line argument) -static const int MIN_INSTANTSEND_DEPTH = 0; -static const int MAX_INSTANTSEND_DEPTH = 60; -/// Default number of "pseudo-confirmations" for an InstantSend tx -static const int DEFAULT_INSTANTSEND_DEPTH = 5; - static const int MIN_INSTANTSEND_PROTO_VERSION = 70209; /// For how long we are going to accept votes/locks @@ -146,8 +138,6 @@ class CInstantSend bool IsLockedInstantSendTransaction(const uint256& txHash); /// Get the actual number of accepted lock signatures int GetTransactionLockSignatures(const uint256& txHash); - /// Get instantsend confirmations (only) - int GetConfirmations(const uint256 &nTXHash); /// Remove expired entries from maps void CheckAndRemove(); diff --git a/src/qt/guiconstants.h b/src/qt/guiconstants.h index e07041f871ae..db2278d930c1 100644 --- a/src/qt/guiconstants.h +++ b/src/qt/guiconstants.h @@ -35,6 +35,8 @@ static const bool DEFAULT_SPLASHSCREEN = true; #define COLOR_TX_STATUS_DANGER QColor(200, 100, 100) /* Transaction list -- TX status decoration - default color */ #define COLOR_BLACK QColor(0, 0, 0) +/* Transaction list -- TX status decoration - LockedByInstantSend color */ +#define COLOR_TX_STATUS_LOCKED QColor(0, 128, 255) /* Tooltips longer than this (in characters) are converted into rich text, so that they can be word-wrapped. diff --git a/src/qt/transactionrecord.cpp b/src/qt/transactionrecord.cpp index 0ca99ec787eb..8376cef1c284 100644 --- a/src/qt/transactionrecord.cpp +++ b/src/qt/transactionrecord.cpp @@ -292,6 +292,7 @@ void TransactionRecord::updateStatus(const CWalletTx &wtx) } else { + status.lockedByInstantSend = wtx.IsLockedByInstantSend(); if (status.depth < 0) { status.status = TransactionStatus::Conflicted; diff --git a/src/qt/transactionrecord.h b/src/qt/transactionrecord.h index 0dca6d2419fa..3a0b903ed13e 100644 --- a/src/qt/transactionrecord.h +++ b/src/qt/transactionrecord.h @@ -42,6 +42,8 @@ class TransactionStatus /// Transaction counts towards available balance bool countsForBalance; + /// Transaction was locked via InstantSend + bool lockedByInstantSend; /// Sorting key based on status std::string sortKey; diff --git a/src/qt/transactiontablemodel.cpp b/src/qt/transactiontablemodel.cpp index d24087aca6de..db16222d9149 100644 --- a/src/qt/transactiontablemodel.cpp +++ b/src/qt/transactiontablemodel.cpp @@ -484,6 +484,24 @@ QString TransactionTableModel::formatTxAmount(const TransactionRecord *wtx, bool return QString(str); } +QIcon IconWithShiftedColor(const QString& filename, bool shift) +{ + if (!shift) + return QIcon(filename); + + QImage img(filename); + img = img.convertToFormat(QImage::Format_ARGB32); + for (int x = img.width(); x--; ) + { + for (int y = img.height(); y--; ) + { + const QRgb rgb = img.pixel(x, y); + img.setPixel(x, y, qRgba(qRed(rgb), qGreen(rgb), qBlue(rgb)+128, qAlpha(rgb))); + } + } + return QIcon(QPixmap::fromImage(img)); +} + QVariant TransactionTableModel::txStatusDecoration(const TransactionRecord *wtx) const { QString theme = GUIUtil::getThemeName(); @@ -495,17 +513,19 @@ QVariant TransactionTableModel::txStatusDecoration(const TransactionRecord *wtx) case TransactionStatus::Offline: return COLOR_TX_STATUS_OFFLINE; case TransactionStatus::Unconfirmed: + // TODO: use special icon for InstantSend 0-conf return QIcon(":/icons/" + theme + "/transaction_0"); case TransactionStatus::Abandoned: return QIcon(":/icons/" + theme + "/transaction_abandoned"); case TransactionStatus::Confirming: switch(wtx->status.depth) { - case 1: return QIcon(":/icons/" + theme + "/transaction_1"); - case 2: return QIcon(":/icons/" + theme + "/transaction_2"); - case 3: return QIcon(":/icons/" + theme + "/transaction_3"); - case 4: return QIcon(":/icons/" + theme + "/transaction_4"); - default: return QIcon(":/icons/" + theme + "/transaction_5"); + // TODO: use special icons for InstantSend instead of color shifting + case 1: return IconWithShiftedColor(":/icons/" + theme + "/transaction_1", wtx->status.lockedByInstantSend); + case 2: return IconWithShiftedColor(":/icons/" + theme + "/transaction_2", wtx->status.lockedByInstantSend); + case 3: return IconWithShiftedColor(":/icons/" + theme + "/transaction_3", wtx->status.lockedByInstantSend); + case 4: return IconWithShiftedColor(":/icons/" + theme + "/transaction_4", wtx->status.lockedByInstantSend); + default: return IconWithShiftedColor(":/icons/" + theme + "/transaction_5", wtx->status.lockedByInstantSend); }; case TransactionStatus::Confirmed: return QIcon(":/icons/" + theme + "/transaction_confirmed"); @@ -608,6 +628,10 @@ QVariant TransactionTableModel::data(const QModelIndex &index, int role) const { return COLOR_TX_STATUS_DANGER; } + if(rec->status.lockedByInstantSend) + { + return COLOR_TX_STATUS_LOCKED; + } // Non-confirmed (but not immature) as transactions are grey if(!rec->status.countsForBalance && rec->status.status != TransactionStatus::Immature) { diff --git a/src/qt/walletmodel.cpp b/src/qt/walletmodel.cpp index 168def534fc3..be3c8f837cd1 100644 --- a/src/qt/walletmodel.cpp +++ b/src/qt/walletmodel.cpp @@ -757,7 +757,7 @@ bool WalletModel::transactionCanBeAbandoned(uint256 hash) const { LOCK2(cs_main, wallet->cs_wallet); const CWalletTx *wtx = wallet->GetWalletTx(hash); - if (!wtx || wtx->isAbandoned() || wtx->GetDepthInMainChain() > 0 || wtx->InMempool()) + if (!wtx || wtx->isAbandoned() || wtx->GetDepthInMainChain() > 0 || wtx->IsLockedByInstantSend() || wtx->InMempool()) return false; return true; } diff --git a/src/wallet/rpcwallet.cpp b/src/wallet/rpcwallet.cpp index 9fe2db850f5b..f681603d568f 100644 --- a/src/wallet/rpcwallet.cpp +++ b/src/wallet/rpcwallet.cpp @@ -59,7 +59,7 @@ void EnsureWalletIsUnlocked() void WalletTxToJSON(const CWalletTx& wtx, UniValue& entry) { - int confirms = wtx.GetDepthInMainChain(false); + int confirms = wtx.GetDepthInMainChain(); bool fLocked = instantsend.IsLockedInstantSendTransaction(wtx.GetHash()); entry.push_back(Pair("confirmations", confirms)); entry.push_back(Pair("instantlock", fLocked)); @@ -658,12 +658,12 @@ UniValue getreceivedbyaddress(const JSONRPCRequest& request) if (request.fHelp || request.params.size() < 1 || request.params.size() > 3) throw std::runtime_error( - "getreceivedbyaddress \"address\" ( minconf addlockconf )\n" + "getreceivedbyaddress \"address\" ( minconf addlocked )\n" "\nReturns the total amount received by the given address in transactions with at least minconf confirmations.\n" "\nArguments:\n" "1. \"address\" (string, required) The absolute address for transactions.\n" "2. minconf (numeric, optional, default=1) Only include transactions confirmed at least this many times.\n" - "3. addlockconf (bool, optional, default=false) Whether to add " + std::to_string(nInstantSendDepth) + " confirmations to transactions locked via InstantSend.\n" + "3. addlocked (bool, optional, default=false) Whether to include transactions locked via InstantSend.\n" "\nResult:\n" "amount (numeric) The total amount in " + CURRENCY_UNIT + " received at this address.\n" "\nExamples:\n" @@ -692,7 +692,7 @@ UniValue getreceivedbyaddress(const JSONRPCRequest& request) int nMinDepth = 1; if (request.params.size() > 1) nMinDepth = request.params[1].get_int(); - bool fAddLockConf = (request.params.size() > 2 && request.params[2].get_bool()); + bool fAddLocked = (request.params.size() > 2 && request.params[2].get_bool()); // Tally CAmount nAmount = 0; @@ -704,7 +704,7 @@ UniValue getreceivedbyaddress(const JSONRPCRequest& request) BOOST_FOREACH(const CTxOut& txout, wtx.tx->vout) if (txout.scriptPubKey == scriptPubKey) - if (wtx.GetDepthInMainChain(fAddLockConf) >= nMinDepth) + if ((wtx.GetDepthInMainChain() >= nMinDepth) || (fAddLocked && wtx.IsLockedByInstantSend())) nAmount += txout.nValue; } @@ -719,12 +719,12 @@ UniValue getreceivedbyaccount(const JSONRPCRequest& request) if (request.fHelp || request.params.size() < 1 || request.params.size() > 3) throw std::runtime_error( - "getreceivedbyaccount \"account\" ( minconf addlockconf )\n" + "getreceivedbyaccount \"account\" ( minconf addlocked )\n" "\nDEPRECATED. Returns the total amount received by addresses with in transactions with specified minimum number of confirmations.\n" "\nArguments:\n" "1. \"account\" (string, required) The selected account, may be the default account using \"\".\n" "2. minconf (numeric, optional, default=1) Only include transactions confirmed at least this many times.\n" - "3. addlockconf (bool, optional, default=false) Whether to add " + std::to_string(nInstantSendDepth) + " confirmations to transactions locked via InstantSend.\n" + "3. addlocked (bool, optional, default=false) Whether to include transactions locked via InstantSend.\n" "\nResult:\n" "amount (numeric) The total amount in " + CURRENCY_UNIT + " received for this account.\n" "\nExamples:\n" @@ -744,7 +744,7 @@ UniValue getreceivedbyaccount(const JSONRPCRequest& request) int nMinDepth = 1; if (request.params.size() > 1) nMinDepth = request.params[1].get_int(); - bool fAddLockConf = (request.params.size() > 2 && request.params[2].get_bool()); + bool fAddLocked = (request.params.size() > 2 && request.params[2].get_bool()); // Get the set of pub keys assigned to account std::string strAccount = AccountFromValue(request.params[0]); @@ -762,7 +762,7 @@ UniValue getreceivedbyaccount(const JSONRPCRequest& request) { CTxDestination address; if (ExtractDestination(txout.scriptPubKey, address) && IsMine(*pwalletMain, address) && setAddress.count(address)) - if (wtx.GetDepthInMainChain(fAddLockConf) >= nMinDepth) + if ((wtx.GetDepthInMainChain() >= nMinDepth) || (fAddLocked && wtx.IsLockedByInstantSend())) nAmount += txout.nValue; } } @@ -777,7 +777,7 @@ UniValue getbalance(const JSONRPCRequest& request) if (request.fHelp || request.params.size() > 4) throw std::runtime_error( - "getbalance ( \"account\" minconf addlockconf include_watchonly )\n" + "getbalance ( \"account\" minconf addlocked include_watchonly )\n" "\nIf account is not specified, returns the server's total available balance.\n" "If account is specified (DEPRECATED), returns the balance in the account.\n" "Note that the account \"\" is not the same as leaving the parameter out.\n" @@ -785,7 +785,7 @@ UniValue getbalance(const JSONRPCRequest& request) "\nArguments:\n" "1. \"account\" (string, optional) DEPRECATED. The selected account, or \"*\" for entire wallet. It may be the default account using \"\".\n" "2. minconf (numeric, optional, default=1) Only include transactions confirmed at least this many times.\n" - "3. addlockconf (bool, optional, default=false) Whether to add " + std::to_string(nInstantSendDepth) + " confirmations to transactions locked via InstantSend.\n" + "3. addlocked (bool, optional, default=false) Whether to add balance from transactions locked via InstantSend.\n" "4. include_watchonly (bool, optional, default=false) Also include balance in watch-only addresses (see 'importaddress')\n" "\nResult:\n" "amount (numeric) The total amount in " + CURRENCY_UNIT + " received for this account.\n" @@ -806,7 +806,7 @@ UniValue getbalance(const JSONRPCRequest& request) int nMinDepth = 1; if (request.params.size() > 1) nMinDepth = request.params[1].get_int(); - bool fAddLockConf = (request.params.size() > 2 && request.params[2].get_bool()); + bool fAddLocked = (request.params.size() > 2 && request.params[2].get_bool()); isminefilter filter = ISMINE_SPENDABLE; if(request.params.size() > 3) if(request.params[3].get_bool()) @@ -828,7 +828,7 @@ UniValue getbalance(const JSONRPCRequest& request) std::list listReceived; std::list listSent; wtx.GetAmounts(listReceived, listSent, allFee, strSentAccount, filter); - if (wtx.GetDepthInMainChain(fAddLockConf) >= nMinDepth) + if ((wtx.GetDepthInMainChain() >= nMinDepth) || (fAddLocked && wtx.IsLockedByInstantSend())) { BOOST_FOREACH(const COutputEntry& r, listReceived) nBalance += r.amount; @@ -842,7 +842,7 @@ UniValue getbalance(const JSONRPCRequest& request) std::string strAccount = AccountFromValue(request.params[0]); - CAmount nBalance = pwalletMain->GetAccountBalance(strAccount, nMinDepth, filter, fAddLockConf); + CAmount nBalance = pwalletMain->GetAccountBalance(strAccount, nMinDepth, filter, fAddLocked); return ValueFromAmount(nBalance); } @@ -917,7 +917,7 @@ UniValue sendfrom(const JSONRPCRequest& request) if (request.fHelp || request.params.size() < 3 || request.params.size() > 7) throw std::runtime_error( - "sendfrom \"fromaccount\" \"toaddress\" amount ( minconf addlockconf \"comment\" \"comment_to\" )\n" + "sendfrom \"fromaccount\" \"toaddress\" amount ( minconf addlocked \"comment\" \"comment_to\" )\n" "\nDEPRECATED (use sendtoaddress). Sent an amount from an account to a absolute address." + HelpRequiringPassphrase() + "\n" "\nArguments:\n" @@ -928,7 +928,7 @@ UniValue sendfrom(const JSONRPCRequest& request) "2. \"toaddress\" (string, required) The absolute address to send funds to.\n" "3. amount (numeric or string, required) The amount in " + CURRENCY_UNIT + " (transaction fee is added on top).\n" "4. minconf (numeric, optional, default=1) Only use funds with at least this many confirmations.\n" - "5. addlockconf (bool, optional, default=false) Whether to add " + std::to_string(nInstantSendDepth) + " confirmations to transactions locked via InstantSend.\n" + "5. addlocked (bool, optional, default=false) Whether to include transactions locked via InstantSend.\n" "6. \"comment\" (string, optional) A comment used to store what the transaction is for. \n" " This is not part of the transaction, just kept in your wallet.\n" "7. \"comment_to\" (string, optional) An optional comment to store the name of the person or organization \n" @@ -957,7 +957,7 @@ UniValue sendfrom(const JSONRPCRequest& request) int nMinDepth = 1; if (request.params.size() > 3) nMinDepth = request.params[3].get_int(); - bool fAddLockConf = (request.params.size() > 4 && request.params[4].get_bool()); + bool fAddLocked = (request.params.size() > 4 && request.params[4].get_bool()); CWalletTx wtx; wtx.strFromAccount = strAccount; @@ -969,7 +969,7 @@ UniValue sendfrom(const JSONRPCRequest& request) EnsureWalletIsUnlocked(); // Check funds - CAmount nBalance = pwalletMain->GetAccountBalance(strAccount, nMinDepth, ISMINE_SPENDABLE, fAddLockConf); + CAmount nBalance = pwalletMain->GetAccountBalance(strAccount, nMinDepth, ISMINE_SPENDABLE, fAddLocked); if (nAmount > nBalance) throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, "Account has insufficient funds"); @@ -986,7 +986,7 @@ UniValue sendmany(const JSONRPCRequest& request) if (request.fHelp || request.params.size() < 2 || request.params.size() > 8) throw std::runtime_error( - "sendmany \"fromaccount\" {\"address\":amount,...} ( minconf addlockconf \"comment\" [\"address\",...] subtractfeefromamount use_is use_ps )\n" + "sendmany \"fromaccount\" {\"address\":amount,...} ( minconf addlocked \"comment\" [\"address\",...] subtractfeefromamount use_is use_ps )\n" "\nSend multiple times. Amounts are double-precision floating point numbers." + HelpRequiringPassphrase() + "\n" "\nArguments:\n" @@ -997,7 +997,7 @@ UniValue sendmany(const JSONRPCRequest& request) " ,...\n" " }\n" "3. minconf (numeric, optional, default=1) Only use the balance confirmed at least this many times.\n" - "4. addlockconf (bool, optional, default=false) Whether to add " + std::to_string(nInstantSendDepth) + " confirmations to transactions locked via InstantSend.\n" + "4. addlocked (bool, optional, default=false) Whether to include transactions locked via InstantSend.\n" "5. \"comment\" (string, optional) A comment\n" "6. subtractfeefromamount (array, optional) A json array with addresses.\n" " The fee will be equally deducted from the amount of each selected address.\n" @@ -1031,7 +1031,7 @@ UniValue sendmany(const JSONRPCRequest& request) int nMinDepth = 1; if (request.params.size() > 2) nMinDepth = request.params[2].get_int(); - bool fAddLockConf = (request.params.size() > 3 && request.params[3].get_bool()); + bool fAddLocked = (request.params.size() > 3 && request.params[3].get_bool()); CWalletTx wtx; wtx.strFromAccount = strAccount; @@ -1077,7 +1077,7 @@ UniValue sendmany(const JSONRPCRequest& request) EnsureWalletIsUnlocked(); // Check funds - CAmount nBalance = pwalletMain->GetAccountBalance(strAccount, nMinDepth, ISMINE_SPENDABLE, fAddLockConf); + CAmount nBalance = pwalletMain->GetAccountBalance(strAccount, nMinDepth, ISMINE_SPENDABLE, fAddLocked); if (totalAmount > nBalance) throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, "Account has insufficient funds"); @@ -1178,7 +1178,7 @@ UniValue ListReceived(const UniValue& params, bool fByAccounts) int nMinDepth = 1; if (params.size() > 0) nMinDepth = params[0].get_int(); - bool fAddLockConf = (params.size() > 1 && params[1].get_bool()); + bool fAddLocked = (params.size() > 1 && params[1].get_bool()); // Whether to include empty accounts bool fIncludeEmpty = false; @@ -1199,8 +1199,8 @@ UniValue ListReceived(const UniValue& params, bool fByAccounts) if (wtx.IsCoinBase() || !CheckFinalTx(*wtx.tx)) continue; - int nDepth = wtx.GetDepthInMainChain(fAddLockConf); - if (nDepth < nMinDepth) + int nDepth = wtx.GetDepthInMainChain(); + if ((nDepth < nMinDepth) && !(fAddLocked && wtx.IsLockedByInstantSend())) continue; BOOST_FOREACH(const CTxOut& txout, wtx.tx->vout) @@ -1304,11 +1304,11 @@ UniValue listreceivedbyaddress(const JSONRPCRequest& request) if (request.fHelp || request.params.size() > 4) throw std::runtime_error( - "listreceivedbyaddress ( minconf addlockconf include_empty include_watchonly)\n" - "\nList balances by receiving address.\n" + "listreceivedbyaddress ( minconf addlocked include_empty include_watchonly)\n" + "\nList incoming payments grouped by receiving address.\n" "\nArguments:\n" "1. minconf (numeric, optional, default=1) The minimum number of confirmations before payments are included.\n" - "2. addlockconf (bool, optional, default=false) Whether to add " + std::to_string(nInstantSendDepth) + " confirmations to transactions locked via InstantSend.\n" + "2. addlocked (bool, optional, default=false) Whether to include transactions locked via InstantSend.\n" "3. include_empty (bool, optional, default=false) Whether to include addresses that haven't received any payments.\n" "4. include_watchonly (bool, optional, default=false) Whether to include watch-only addresses (see 'importaddress').\n" @@ -1320,8 +1320,8 @@ UniValue listreceivedbyaddress(const JSONRPCRequest& request) " \"account\" : \"accountname\", (string) DEPRECATED. The account of the receiving address. The default account is \"\".\n" " \"amount\" : x.xxx, (numeric) The total amount in " + CURRENCY_UNIT + " received by the address\n" " \"confirmations\" : n (numeric) The number of confirmations of the most recent transaction included.\n" - " If 'addlockconf' is true, the minimum number of confirmations is calculated\n" - " including additional " + std::to_string(nInstantSendDepth) + " confirmations for transactions locked via InstantSend\n" + " If 'addlocked' is true, the number of confirmations can be less than\n" + " configured for transactions locked via InstantSend\n" " \"label\" : \"label\", (string) A comment for the address/transaction, if any\n" " \"txids\": [\n" " n, (numeric) The ids of transactions received with the address \n" @@ -1349,11 +1349,11 @@ UniValue listreceivedbyaccount(const JSONRPCRequest& request) if (request.fHelp || request.params.size() > 4) throw std::runtime_error( - "listreceivedbyaccount ( minconf addlockconf include_empty include_watchonly)\n" - "\nDEPRECATED. List balances by account.\n" + "listreceivedbyaccount ( minconf addlocked include_empty include_watchonly)\n" + "\nDEPRECATED. List incoming payments grouped by account.\n" "\nArguments:\n" "1. minconf (numeric, optional, default=1) The minimum number of confirmations before payments are included.\n" - "2. addlockconf (bool, optional, default=false) Whether to add " + std::to_string(nInstantSendDepth) + " confirmations to transactions locked via InstantSend.\n" + "2. addlocked (bool, optional, default=false) Whether to include transactions locked via InstantSend.\n" "3. include_empty (bool, optional, default=false) Whether to include accounts that haven't received any payments.\n" "4. include_watchonly (bool, optional, default=false) Whether to include watch-only addresses (see 'importaddress').\n" @@ -1424,7 +1424,7 @@ void ListTransactions(const CWalletTx& wtx, const std::string& strAccount, int n } // Received - if (listReceived.size() > 0 && wtx.GetDepthInMainChain() >= nMinDepth) + if (listReceived.size() > 0 && ((wtx.GetDepthInMainChain() >= nMinDepth) || wtx.IsLockedByInstantSend())) { BOOST_FOREACH(const COutputEntry& r, listReceived) { @@ -1616,11 +1616,11 @@ UniValue listaccounts(const JSONRPCRequest& request) if (request.fHelp || request.params.size() > 3) throw std::runtime_error( - "listaccounts ( minconf addlockconf include_watchonly)\n" + "listaccounts ( minconf addlocked include_watchonly)\n" "\nDEPRECATED. Returns Object that has account names as keys, account balances as values.\n" "\nArguments:\n" "1. minconf (numeric, optional, default=1) Only include transactions with at least this many confirmations\n" - "2. addlockconf (bool, optional, default=false) Whether to add " + std::to_string(nInstantSendDepth) + " confirmations to transactions locked via InstantSend.\n" + "2. addlocked (bool, optional, default=false) Whether to include transactions locked via InstantSend.\n" "3. include_watchonly (bool, optional, default=false) Include balances in watch-only addresses (see 'importaddress')\n" "\nResult:\n" "{ (json object where keys are account names, and values are numeric balances\n" @@ -1643,7 +1643,7 @@ UniValue listaccounts(const JSONRPCRequest& request) int nMinDepth = 1; if (request.params.size() > 0) nMinDepth = request.params[0].get_int(); - bool fAddLockConf = (request.params.size() > 1 && request.params[1].get_bool()); + bool fAddLocked = (request.params.size() > 1 && request.params[1].get_bool()); isminefilter includeWatchonly = ISMINE_SPENDABLE; if(request.params.size() > 2) if(request.params[2].get_bool()) @@ -1662,14 +1662,14 @@ UniValue listaccounts(const JSONRPCRequest& request) std::string strSentAccount; std::list listReceived; std::list listSent; - int nDepth = wtx.GetDepthInMainChain(fAddLockConf); + int nDepth = wtx.GetDepthInMainChain(); if (wtx.GetBlocksToMaturity() > 0 || nDepth < 0) continue; wtx.GetAmounts(listReceived, listSent, nFee, strSentAccount, includeWatchonly); mapAccountBalances[strSentAccount] -= nFee; BOOST_FOREACH(const COutputEntry& s, listSent) mapAccountBalances[strSentAccount] -= s.amount; - if (nDepth >= nMinDepth) + if ((nDepth >= nMinDepth) || (fAddLocked && wtx.IsLockedByInstantSend())) { BOOST_FOREACH(const COutputEntry& r, listReceived) if (pwalletMain->mapAddressBook.count(r.destination)) @@ -1785,7 +1785,7 @@ UniValue listsinceblock(const JSONRPCRequest& request) { CWalletTx tx = (*it).second; - if (depth == -1 || tx.GetDepthInMainChain(false) < depth) + if (depth == -1 || tx.GetDepthInMainChain() < depth) ListTransactions(tx, "*", 0, true, transactions, filter); } @@ -2857,11 +2857,11 @@ static const CRPCCommand commands[] = { "wallet", "getaccountaddress", &getaccountaddress, true, {"account"} }, { "wallet", "getaccount", &getaccount, true, {"address"} }, { "wallet", "getaddressesbyaccount", &getaddressesbyaccount, true, {"account"} }, - { "wallet", "getbalance", &getbalance, false, {"account","minconf","addlockconf","include_watchonly"} }, + { "wallet", "getbalance", &getbalance, false, {"account","minconf","addlocked","include_watchonly"} }, { "wallet", "getnewaddress", &getnewaddress, true, {"account"} }, { "wallet", "getrawchangeaddress", &getrawchangeaddress, true, {} }, - { "wallet", "getreceivedbyaccount", &getreceivedbyaccount, false, {"account","minconf","addlockconf"} }, - { "wallet", "getreceivedbyaddress", &getreceivedbyaddress, false, {"address","minconf","addlockconf"} }, + { "wallet", "getreceivedbyaccount", &getreceivedbyaccount, false, {"account","minconf","addlocked"} }, + { "wallet", "getreceivedbyaddress", &getreceivedbyaddress, false, {"address","minconf","addlocked"} }, { "wallet", "gettransaction", &gettransaction, false, {"txid","include_watchonly"} }, { "wallet", "getunconfirmedbalance", &getunconfirmedbalance, false, {} }, { "wallet", "getwalletinfo", &getwalletinfo, false, {} }, @@ -2872,19 +2872,19 @@ static const CRPCCommand commands[] = { "wallet", "importprunedfunds", &importprunedfunds, true, {"rawtransaction","txoutproof"} }, { "wallet", "importpubkey", &importpubkey, true, {"pubkey","label","rescan"} }, { "wallet", "keypoolrefill", &keypoolrefill, true, {"newsize"} }, - { "wallet", "listaccounts", &listaccounts, false, {"minconf","addlockconf","include_watchonly"} }, + { "wallet", "listaccounts", &listaccounts, false, {"minconf","addlocked","include_watchonly"} }, { "wallet", "listaddressgroupings", &listaddressgroupings, false, {} }, { "wallet", "listaddressbalances", &listaddressbalances, false, {"minamount"} }, { "wallet", "listlockunspent", &listlockunspent, false, {} }, - { "wallet", "listreceivedbyaccount", &listreceivedbyaccount, false, {"minconf","addlockconf","include_empty","include_watchonly"} }, - { "wallet", "listreceivedbyaddress", &listreceivedbyaddress, false, {"minconf","addlockconf","include_empty","include_watchonly"} }, + { "wallet", "listreceivedbyaccount", &listreceivedbyaccount, false, {"minconf","addlocked","include_empty","include_watchonly"} }, + { "wallet", "listreceivedbyaddress", &listreceivedbyaddress, false, {"minconf","addlocked","include_empty","include_watchonly"} }, { "wallet", "listsinceblock", &listsinceblock, false, {"blockhash","target_confirmations","include_watchonly"} }, { "wallet", "listtransactions", &listtransactions, false, {"account","count","skip","include_watchonly"} }, { "wallet", "listunspent", &listunspent, false, {"minconf","maxconf","addresses","include_unsafe"} }, { "wallet", "lockunspent", &lockunspent, true, {"unlock","transactions"} }, { "wallet", "move", &movecmd, false, {"fromaccount","toaccount","amount","minconf","comment"} }, - { "wallet", "sendfrom", &sendfrom, false, {"fromaccount","toaddress","amount","minconf","addlockconf","comment","comment_to"} }, - { "wallet", "sendmany", &sendmany, false, {"fromaccount","amounts","minconf","addlockconf","comment","subtractfeefrom"} }, + { "wallet", "sendfrom", &sendfrom, false, {"fromaccount","toaddress","amount","minconf","addlocked","comment","comment_to"} }, + { "wallet", "sendmany", &sendmany, false, {"fromaccount","amounts","minconf","addlocked","comment","subtractfeefrom"} }, { "wallet", "sendtoaddress", &sendtoaddress, false, {"address","amount","comment","comment_to","subtractfeefromamount"} }, { "wallet", "setaccount", &setaccount, true, {"address","account"} }, { "wallet", "settxfee", &settxfee, true, {"amount"} }, diff --git a/src/wallet/wallet.cpp b/src/wallet/wallet.cpp index 3a9a3c8790df..f62db6544812 100644 --- a/src/wallet/wallet.cpp +++ b/src/wallet/wallet.cpp @@ -1258,7 +1258,7 @@ bool CWallet::AbandonTransaction(const uint256& hashTx) // Can't mark abandoned if confirmed or in mempool assert(mapWallet.count(hashTx)); CWalletTx& origtx = mapWallet[hashTx]; - if (origtx.GetDepthInMainChain() > 0 || origtx.InMempool()) { + if (origtx.GetDepthInMainChain() > 0 || origtx.InMempool() || origtx.IsLockedByInstantSend()) { return false; } @@ -1944,7 +1944,7 @@ void CWallet::ReacceptWalletTransactions() int nDepth = wtx.GetDepthInMainChain(); - if (!wtx.IsCoinBase() && (nDepth == 0 && !wtx.isAbandoned())) { + if (!wtx.IsCoinBase() && (nDepth == 0 && !wtx.IsLockedByInstantSend() && !wtx.isAbandoned())) { mapSorted.insert(std::make_pair(wtx.nOrderPos, &wtx)); } } @@ -2193,7 +2193,7 @@ CAmount CWalletTx::GetDenominatedCredit(bool unconfirmed, bool fUseCache) const if (IsCoinBase() && GetBlocksToMaturity() > 0) return 0; - int nDepth = GetDepthInMainChain(false); + int nDepth = GetDepthInMainChain(); if(nDepth < 0) return 0; bool isUnconfirmed = IsTrusted() && nDepth == 0; @@ -2257,6 +2257,8 @@ bool CWalletTx::IsTrusted() const return true; if (nDepth < 0) return false; + if (IsLockedByInstantSend()) + return true; if (!bSpendZeroConfChange || !IsFromMe(ISMINE_ALL)) // using wtx's cached debit return false; @@ -2500,7 +2502,7 @@ CAmount CWallet::GetUnconfirmedBalance() const for (std::map::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { const CWalletTx* pcoin = &(*it).second; - if (!pcoin->IsTrusted() && pcoin->GetDepthInMainChain() == 0 && pcoin->InMempool()) + if (!pcoin->IsTrusted() && pcoin->GetDepthInMainChain() == 0 && !pcoin->IsLockedByInstantSend() && pcoin->InMempool()) nTotal += pcoin->GetAvailableCredit(); } } @@ -2545,7 +2547,7 @@ CAmount CWallet::GetUnconfirmedWatchOnlyBalance() const for (std::map::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { const CWalletTx* pcoin = &(*it).second; - if (!pcoin->IsTrusted() && pcoin->GetDepthInMainChain() == 0 && pcoin->InMempool()) + if (!pcoin->IsTrusted() && pcoin->GetDepthInMainChain() == 0 && !pcoin->IsLockedByInstantSend() && pcoin->InMempool()) nTotal += pcoin->GetAvailableWatchOnlyCredit(); } } @@ -2588,7 +2590,7 @@ void CWallet::AvailableCoins(std::vector& vCoins, bool fOnlyConfirmed, if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0) continue; - int nDepth = pcoin->GetDepthInMainChain(false); + int nDepth = pcoin->GetDepthInMainChain(); // do not use IX for inputs that have less then nInstantSendConfirmationsRequired blockchain confirmations if (fUseInstantSend && nDepth < nInstantSendConfirmationsRequired) continue; @@ -3276,7 +3278,7 @@ int CWallet::CountInputsWithAmount(CAmount nInputAmount) { const CWalletTx* pcoin = &(*it).second; if (pcoin->IsTrusted()){ - int nDepth = pcoin->GetDepthInMainChain(false); + int nDepth = pcoin->GetDepthInMainChain(); for (unsigned int i = 0; i < pcoin->tx->vout.size(); i++) { COutput out = COutput(pcoin, i, nDepth, true, true); @@ -4315,7 +4317,7 @@ std::map CWallet::GetAddressBalances() continue; int nDepth = pcoin->GetDepthInMainChain(); - if (nDepth < (pcoin->IsFromMe(ISMINE_ALL) ? 0 : 1)) + if ((nDepth < (pcoin->IsFromMe(ISMINE_ALL) ? 0 : 1)) && !pcoin->IsLockedByInstantSend()) continue; for (unsigned int i = 0; i < pcoin->tx->vout.size(); i++) @@ -4431,13 +4433,13 @@ std::set< std::set > CWallet::GetAddressGroupings() return ret; } -CAmount CWallet::GetAccountBalance(const std::string& strAccount, int nMinDepth, const isminefilter& filter, bool fAddLockConf) +CAmount CWallet::GetAccountBalance(const std::string& strAccount, int nMinDepth, const isminefilter& filter, bool fAddLocked) { CWalletDB walletdb(strWalletFile); - return GetAccountBalance(walletdb, strAccount, nMinDepth, filter, fAddLockConf); + return GetAccountBalance(walletdb, strAccount, nMinDepth, filter, fAddLocked); } -CAmount CWallet::GetAccountBalance(CWalletDB& walletdb, const std::string& strAccount, int nMinDepth, const isminefilter& filter, bool fAddLockConf) +CAmount CWallet::GetAccountBalance(CWalletDB& walletdb, const std::string& strAccount, int nMinDepth, const isminefilter& filter, bool fAddLocked) { CAmount nBalance = 0; @@ -4445,13 +4447,13 @@ CAmount CWallet::GetAccountBalance(CWalletDB& walletdb, const std::string& strAc for (std::map::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { const CWalletTx& wtx = (*it).second; - if (!CheckFinalTx(wtx) || wtx.GetBlocksToMaturity() > 0 || wtx.GetDepthInMainChain(fAddLockConf) < 0) + if (!CheckFinalTx(wtx) || wtx.GetBlocksToMaturity() > 0 || wtx.GetDepthInMainChain() < 0) continue; CAmount nReceived, nSent, nFee; wtx.GetAccountAmounts(strAccount, nReceived, nSent, nFee, filter); - if (nReceived != 0 && wtx.GetDepthInMainChain(fAddLockConf) >= nMinDepth) + if (nReceived != 0 && ((wtx.GetDepthInMainChain() >= nMinDepth) || (fAddLocked && wtx.IsLockedByInstantSend()))) nBalance += nReceived; nBalance -= nSent + nFee; } @@ -5347,7 +5349,7 @@ void CMerkleTx::SetMerkleBranch(const CBlockIndex* pindex, int posInBlock) nIndex = posInBlock; } -int CMerkleTx::GetDepthInMainChain(const CBlockIndex* &pindexRet, bool enableIX) const +int CMerkleTx::GetDepthInMainChain(const CBlockIndex* &pindexRet) const { int nResult; @@ -5374,12 +5376,14 @@ int CMerkleTx::GetDepthInMainChain(const CBlockIndex* &pindexRet, bool enableIX) } } - if(enableIX && nResult < 6 && instantsend.IsLockedInstantSendTransaction(GetHash())) - return nInstantSendDepth + nResult; - return nResult; } +bool CMerkleTx::IsLockedByInstantSend() const +{ + return instantsend.IsLockedInstantSendTransaction(GetHash()); +} + int CMerkleTx::GetBlocksToMaturity() const { if (!IsCoinBase()) diff --git a/src/wallet/wallet.h b/src/wallet/wallet.h index 43af83bd055a..39c2e3df548f 100644 --- a/src/wallet/wallet.h +++ b/src/wallet/wallet.h @@ -272,9 +272,10 @@ class CMerkleTx * 0 : in memory pool, waiting to be included in a block * >=1 : this many blocks deep in the main chain */ - int GetDepthInMainChain(const CBlockIndex* &pindexRet, bool enableIX = true) const; - int GetDepthInMainChain(bool enableIX = true) const { const CBlockIndex *pindexRet; return GetDepthInMainChain(pindexRet, enableIX); } + int GetDepthInMainChain(const CBlockIndex* &pindexRet) const; + int GetDepthInMainChain() const { const CBlockIndex *pindexRet; return GetDepthInMainChain(pindexRet); } bool IsInMainChain() const { const CBlockIndex *pindexRet; return GetDepthInMainChain(pindexRet) > 0; } + bool IsLockedByInstantSend() const; int GetBlocksToMaturity() const; /** Pass this transaction to the mempool. Fails if absolute fee exceeds absurd fee. */ bool AcceptToMemoryPool(const CAmount& nAbsurdFee, CValidationState& state); @@ -977,8 +978,8 @@ class CWallet : public CCryptoKeyStore, public CValidationInterface std::set< std::set > GetAddressGroupings(); std::map GetAddressBalances(); - CAmount GetAccountBalance(const std::string& strAccount, int nMinDepth, const isminefilter& filter, bool fAddLockConf); - CAmount GetAccountBalance(CWalletDB& walletdb, const std::string& strAccount, int nMinDepth, const isminefilter& filter, bool fAddLockConf); + CAmount GetAccountBalance(const std::string& strAccount, int nMinDepth, const isminefilter& filter, bool fAddLocked); + CAmount GetAccountBalance(CWalletDB& walletdb, const std::string& strAccount, int nMinDepth, const isminefilter& filter, bool fAddLocked); std::set GetAccountAddresses(const std::string& strAccount) const; isminetype IsMine(const CTxIn& txin) const; From df3dd35e55a48b10a0a714e8ef056f6c069543a1 Mon Sep 17 00:00:00 2001 From: UdjinM6 Date: Sun, 29 Jul 2018 09:39:37 +0300 Subject: [PATCH 030/282] Fix lockedByInstantSend initialization (#2197) --- src/qt/transactionrecord.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/qt/transactionrecord.h b/src/qt/transactionrecord.h index 3a0b903ed13e..a78c882ad930 100644 --- a/src/qt/transactionrecord.h +++ b/src/qt/transactionrecord.h @@ -20,7 +20,7 @@ class TransactionStatus { public: TransactionStatus(): - countsForBalance(false), sortKey(""), + countsForBalance(false), lockedByInstantSend(false), sortKey(""), matures_in(0), status(Offline), depth(0), open_for(0), cur_num_blocks(-1) { } From 025ab93f3bc2c947cc253d5a839e2ef88e76560f Mon Sep 17 00:00:00 2001 From: strophy <32928115+strophy@users.noreply.github.com> Date: Sat, 4 Aug 2018 21:38:57 +0800 Subject: [PATCH 031/282] Fix typo and grammar in PS error message (#2199) * Fix typo * Grammar fix --- src/qt/coincontroldialog.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/qt/coincontroldialog.cpp b/src/qt/coincontroldialog.cpp index 34cdfaf3e25d..c3f489cde1c4 100644 --- a/src/qt/coincontroldialog.cpp +++ b/src/qt/coincontroldialog.cpp @@ -437,7 +437,7 @@ void CoinControlDialog::viewItemChanged(QTreeWidgetItem* item, int column) int nRounds = pwalletMain->GetRealOutpointPrivateSendRounds(outpt); if (coinControl->fUsePrivateSend && nRounds < privateSendClient.nPrivateSendRounds) { QMessageBox::warning(this, windowTitle(), - tr("Non-anonymized input selected. PrivateSend will be disabled.

If you still want to use PrivateSend, please deselect all non-nonymized inputs first and then check PrivateSend checkbox again."), + tr("Non-anonymized input selected. PrivateSend will be disabled.

If you still want to use PrivateSend, please deselect all non-anonymized inputs first and then check the PrivateSend checkbox again."), QMessageBox::Ok, QMessageBox::Ok); coinControl->fUsePrivateSend = false; } From d9dc29d9524aa9fb85dce94b1aa27e4e8db484ac Mon Sep 17 00:00:00 2001 From: UdjinM6 Date: Sat, 4 Aug 2018 16:39:15 +0300 Subject: [PATCH 032/282] Fix mnsync in regtest (#2202) --- src/masternode-sync.cpp | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/src/masternode-sync.cpp b/src/masternode-sync.cpp index a81da5d96086..cda2f067dcd6 100644 --- a/src/masternode-sync.cpp +++ b/src/masternode-sync.cpp @@ -185,22 +185,21 @@ void CMasternodeSync::ProcessTick(CConnman& connman) // QUICK MODE (REGTEST ONLY!) if(Params().NetworkIDString() == CBaseChainParams::REGTEST) { - if(nRequestedMasternodeAttempt <= 2) { + if (nRequestedMasternodeAssets == MASTERNODE_SYNC_WAITING) { connman.PushMessage(pnode, msgMaker.Make(NetMsgType::GETSPORKS)); //get current network sporks - } else if(nRequestedMasternodeAttempt < 4) { + } else if (nRequestedMasternodeAssets == MASTERNODE_SYNC_LIST) { mnodeman.DsegUpdate(pnode, connman); - } else if(nRequestedMasternodeAttempt < 6) { + } else if (nRequestedMasternodeAssets == MASTERNODE_SYNC_MNW) { //sync payment votes if(pnode->nVersion == 70208) { connman.PushMessage(pnode, msgMaker.Make(NetMsgType::MASTERNODEPAYMENTSYNC, mnpayments.GetStorageLimit())); //sync payment votes } else { connman.PushMessage(pnode, msgMaker.Make(NetMsgType::MASTERNODEPAYMENTSYNC)); //sync payment votes } + } else if (nRequestedMasternodeAssets == MASTERNODE_SYNC_GOVERNANCE) { SendGovernanceSyncRequest(pnode, connman); - } else { - nRequestedMasternodeAssets = MASTERNODE_SYNC_FINISHED; } - nRequestedMasternodeAttempt++; + SwitchToNextAsset(connman); connman.ReleaseNodeVector(vNodesCopy); return; } From 848e69eaa3cb2c6df91a1ea7d5ec9e62a30c53b7 Mon Sep 17 00:00:00 2001 From: UdjinM6 Date: Sat, 11 Aug 2018 01:28:30 +0300 Subject: [PATCH 033/282] Add `previousbits` field to `getblocktemplate` output (#2201) * Add `previousbits` field to `getblocktemplate` output * add comment to nPrevBits --- src/miner.cpp | 1 + src/miner.h | 1 + src/rpc/mining.cpp | 2 ++ 3 files changed, 4 insertions(+) diff --git a/src/miner.cpp b/src/miner.cpp index 41df3fca61cd..29e539f9f78d 100644 --- a/src/miner.cpp +++ b/src/miner.cpp @@ -184,6 +184,7 @@ std::unique_ptr BlockAssembler::CreateNewBlock(const CScript& sc UpdateTime(pblock, chainparams.GetConsensus(), pindexPrev); pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, chainparams.GetConsensus()); pblock->nNonce = 0; + pblocktemplate->nPrevBits = pindexPrev->nBits; pblocktemplate->vTxSigOps[0] = GetLegacySigOpCount(*pblock->vtx[0]); CValidationState state; diff --git a/src/miner.h b/src/miner.h index 7a46f18f1303..ab2a5f2fc3a9 100644 --- a/src/miner.h +++ b/src/miner.h @@ -30,6 +30,7 @@ struct CBlockTemplate CBlock block; std::vector vTxFees; std::vector vTxSigOps; + uint32_t nPrevBits; // nBits of previous block (for subsidy calculation) CTxOut txoutMasternode; // masternode payment std::vector voutSuperblock; // superblock payment }; diff --git a/src/rpc/mining.cpp b/src/rpc/mining.cpp index e7acf9960bc2..6b819f0716db 100644 --- a/src/rpc/mining.cpp +++ b/src/rpc/mining.cpp @@ -388,6 +388,7 @@ UniValue getblocktemplate(const JSONRPCRequest& request) " \"sizelimit\" : n, (numeric) limit of block size\n" " \"curtime\" : ttt, (numeric) current timestamp in seconds since epoch (Jan 1 1970 GMT)\n" " \"bits\" : \"xxxxxxxx\", (string) compressed target of next block\n" + " \"previousbits\" : \"xxxxxxxx\", (string) compressed target of current highest block\n" " \"height\" : n (numeric) The height of the next block\n" " \"masternode\" : { (json object) required masternode payee that must be included in the next block\n" " \"payee\" : \"xxxx\", (string) payee address\n" @@ -699,6 +700,7 @@ UniValue getblocktemplate(const JSONRPCRequest& request) result.push_back(Pair("sizelimit", (int64_t)MaxBlockSize(fDIP0001ActiveAtTip))); result.push_back(Pair("curtime", pblock->GetBlockTime())); result.push_back(Pair("bits", strprintf("%08x", pblock->nBits))); + result.push_back(Pair("previousbits", strprintf("%08x", pblocktemplate->nPrevBits))); result.push_back(Pair("height", (int64_t)(pindexPrev->nHeight+1))); UniValue masternodeObj(UniValue::VOBJ); From ba291e32b79a1658d962acb324987c3ad38db09d Mon Sep 17 00:00:00 2001 From: Alexander Block Date: Sat, 11 Aug 2018 00:29:28 +0200 Subject: [PATCH 034/282] Use C++14 standard when building (#2209) We have upgraded CI to use a recent compiler already and thus can also increase the C++ standard now. After this, we'll also have to update Gitian build to work with C++14 as well, but this is going to happen in separate commits/PRs. --- configure.ac | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/configure.ac b/configure.ac index 5ec437a1cbee..be2f1e7c9746 100644 --- a/configure.ac +++ b/configure.ac @@ -53,8 +53,8 @@ case $host in lt_cv_deplibs_check_method="pass_all" ;; esac -dnl Require C++11 compiler (no GNU extensions) -AX_CXX_COMPILE_STDCXX([11], [noext], [mandatory], [nodefault]) +dnl Require C++14 compiler (no GNU extensions) +AX_CXX_COMPILE_STDCXX([14], [noext], [mandatory], [nodefault]) dnl Check if -latomic is required for CHECK_ATOMIC From 309c69c6fff0bf464a0425ab5db6bd7d87f264db Mon Sep 17 00:00:00 2001 From: Alexander Block Date: Sat, 11 Aug 2018 00:30:55 +0200 Subject: [PATCH 035/282] Add support for "help command subCommand" (#2210) --- src/rpc/server.cpp | 17 ++++++++++++----- src/rpc/server.h | 2 +- 2 files changed, 13 insertions(+), 6 deletions(-) diff --git a/src/rpc/server.cpp b/src/rpc/server.cpp index 593ad7e61118..388886de7551 100644 --- a/src/rpc/server.cpp +++ b/src/rpc/server.cpp @@ -177,7 +177,7 @@ std::vector ParseHexO(const UniValue& o, std::string strKey) * Note: This interface may still be subject to change. */ -std::string CRPCTable::help(const std::string& strCommand) const +std::string CRPCTable::help(const std::string& strCommand, const std::string& strSubCommand) const { std::string strRet; std::string category; @@ -201,6 +201,10 @@ std::string CRPCTable::help(const std::string& strCommand) const { JSONRPCRequest jreq; jreq.fHelp = true; + if (!strSubCommand.empty()) { + jreq.params.setArray(); + jreq.params.push_back(strSubCommand); + } rpcfn_type pfn = pcmd->actor; if (setDone.insert(pfn).second) (*pfn)(jreq); @@ -235,21 +239,24 @@ std::string CRPCTable::help(const std::string& strCommand) const UniValue help(const JSONRPCRequest& jsonRequest) { - if (jsonRequest.fHelp || jsonRequest.params.size() > 1) + if (jsonRequest.fHelp || jsonRequest.params.size() > 2) throw std::runtime_error( - "help ( \"command\" )\n" + "help ( \"command\" ) (\"subCommand\")\n" "\nList all commands, or get help for a specified command.\n" "\nArguments:\n" "1. \"command\" (string, optional) The command to get help on\n" + "2. \"subCommand\" (string, optional) The subcommand to get help on. Please not that not all subcommands support this at the moment\n" "\nResult:\n" "\"text\" (string) The help text\n" ); - std::string strCommand; + std::string strCommand, strSubCommand; if (jsonRequest.params.size() > 0) strCommand = jsonRequest.params[0].get_str(); + if (jsonRequest.params.size() > 1) + strSubCommand = jsonRequest.params[1].get_str(); - return tableRPC.help(strCommand); + return tableRPC.help(strCommand, strSubCommand); } diff --git a/src/rpc/server.h b/src/rpc/server.h index f4d6645735e5..5dcf5e26465e 100644 --- a/src/rpc/server.h +++ b/src/rpc/server.h @@ -152,7 +152,7 @@ class CRPCTable public: CRPCTable(); const CRPCCommand* operator[](const std::string& name) const; - std::string help(const std::string& name) const; + std::string help(const std::string& strCommand, const std::string& strSubCommand) const; /** * Execute a method. From 48f4126335dbc622f72d8435a466e9268042e09d Mon Sep 17 00:00:00 2001 From: Alexander Block Date: Sat, 11 Aug 2018 00:33:56 +0200 Subject: [PATCH 036/282] Add new ParseXXX methods to easily parse UniValue values (#2211) --- src/rpc/server.cpp | 48 ++++++++++++++++++++++++++++++++++++++++++++++ src/rpc/server.h | 5 +++++ 2 files changed, 53 insertions(+) diff --git a/src/rpc/server.cpp b/src/rpc/server.cpp index 388886de7551..da7b44af1027 100644 --- a/src/rpc/server.cpp +++ b/src/rpc/server.cpp @@ -25,6 +25,7 @@ #include #include // for to_upper() +#include #include // for unique_ptr #include @@ -173,6 +174,53 @@ std::vector ParseHexO(const UniValue& o, std::string strKey) return ParseHexV(find_value(o, strKey), strKey); } +int32_t ParseInt32V(const UniValue& v, const std::string &strName) +{ + std::string strNum = v.getValStr(); + int32_t num; + if (!ParseInt32(strNum, &num)) + throw JSONRPCError(RPC_INVALID_PARAMETER, strName+" must be a 32bit integer (not '"+strNum+"')"); + return num; +} + +int64_t ParseInt64V(const UniValue& v, const std::string &strName) +{ + std::string strNum = v.getValStr(); + int64_t num; + if (!ParseInt64(strNum, &num)) + throw JSONRPCError(RPC_INVALID_PARAMETER, strName+" must be a 64bit integer (not '"+strNum+"')"); + return num; +} + +double ParseDoubleV(const UniValue& v, const std::string &strName) +{ + std::string strNum = v.getValStr(); + double num; + if (!ParseDouble(strNum, &num)) + throw JSONRPCError(RPC_INVALID_PARAMETER, strName+" must be a be number (not '"+strNum+"')"); + return num; +} + +bool ParseBoolV(const UniValue& v, const std::string &strName) +{ + std::string strBool; + if (v.isBool()) + return v.get_bool(); + else if (v.isNum()) + strBool = itostr(v.get_int()); + else if (v.isStr()) + strBool = v.get_str(); + + std::transform(strBool.begin(), strBool.end(), strBool.begin(), ::tolower); + + if (strBool == "true" || strBool == "yes" || strBool == "1") { + return true; + } else if (strBool == "false" || strBool == "no" || strBool == "0") { + return false; + } + throw JSONRPCError(RPC_INVALID_PARAMETER, strName+" must be true, false, yes, no, 1 or 0 (not '"+strBool+"')"); +} + /** * Note: This interface may still be subject to change. */ diff --git a/src/rpc/server.h b/src/rpc/server.h index 5dcf5e26465e..0d6f6e685bde 100644 --- a/src/rpc/server.h +++ b/src/rpc/server.h @@ -187,6 +187,11 @@ extern uint256 ParseHashO(const UniValue& o, std::string strKey); extern std::vector ParseHexV(const UniValue& v, std::string strName); extern std::vector ParseHexO(const UniValue& o, std::string strKey); +extern int32_t ParseInt32V(const UniValue& v, const std::string &strName); +extern int64_t ParseInt64V(const UniValue& v, const std::string &strName); +extern double ParseDoubleV(const UniValue& v, const std::string &strName); +extern bool ParseBoolV(const UniValue& v, const std::string &strName); + extern int64_t nWalletUnlockTime; extern CAmount AmountFromValue(const UniValue& value); extern UniValue ValueFromAmount(const CAmount& amount); From aca20340c08d007fa62d24b656ecac32e3a1d8ec Mon Sep 17 00:00:00 2001 From: Alexander Block Date: Sat, 11 Aug 2018 00:35:52 +0200 Subject: [PATCH 037/282] De-duplicate "gobject vote-alias" and "gobject "vote-many" code (#2217) Use same code for both vote modes --- src/rpc/governance.cpp | 137 ++++------------------------------------- 1 file changed, 11 insertions(+), 126 deletions(-) diff --git a/src/rpc/governance.cpp b/src/rpc/governance.cpp index de05a3f53afe..52dcde2c4070 100644 --- a/src/rpc/governance.cpp +++ b/src/rpc/governance.cpp @@ -400,10 +400,12 @@ UniValue gobject(const JSONRPCRequest& request) return returnObj; } - if(strCommand == "vote-many") + if(strCommand == "vote-many" || strCommand == "vote-alias") { - if(request.params.size() != 4) + if(strCommand == "vote-many" && request.params.size() != 4) throw JSONRPCError(RPC_INVALID_PARAMETER, "Correct usage is 'gobject vote-many [funding|valid|delete] [yes|no|abstain]'"); + else if(strCommand == "vote-alias" && request.params.size() != 5) + throw JSONRPCError(RPC_INVALID_PARAMETER, "Correct usage is 'gobject vote-alias [funding|valid|delete] [yes|no|abstain] '"); uint256 hash; std::string strVote; @@ -412,6 +414,10 @@ UniValue gobject(const JSONRPCRequest& request) std::string strVoteSignal = request.params[2].get_str(); std::string strVoteOutcome = request.params[3].get_str(); + std::string strAlias; + if (strCommand == "vote-alias") { + strAlias = request.params[4].get_str(); + } vote_signal_enum_t eVoteSignal = CGovernanceVoting::ConvertVoteSignal(strVoteSignal); if(eVoteSignal == VOTE_SIGNAL_NONE) { @@ -431,6 +437,9 @@ UniValue gobject(const JSONRPCRequest& request) UniValue resultsObj(UniValue::VOBJ); for (const auto& mne : masternodeConfig.getEntries()) { + // skip masternode if using "vote-alias" and it's the wrong masternode + if(strCommand == "vote-alias" && strAlias != mne.getAlias()) continue; + std::string strError; std::vector vchMasterNodeSignature; std::string strMasterNodeSignMessage; @@ -501,130 +510,6 @@ UniValue gobject(const JSONRPCRequest& request) return returnObj; } - - // MASTERNODES CAN VOTE ON GOVERNANCE OBJECTS ON THE NETWORK FOR VARIOUS SIGNALS AND OUTCOMES - if(strCommand == "vote-alias") - { - if(request.params.size() != 5) - throw JSONRPCError(RPC_INVALID_PARAMETER, "Correct usage is 'gobject vote-alias [funding|valid|delete] [yes|no|abstain] '"); - - uint256 hash; - std::string strVote; - - // COLLECT NEEDED PARAMETRS FROM USER - - hash = ParseHashV(request.params[1], "Object hash"); - std::string strVoteSignal = request.params[2].get_str(); - std::string strVoteOutcome = request.params[3].get_str(); - std::string strAlias = request.params[4].get_str(); - - // CONVERT NAMED SIGNAL/ACTION AND CONVERT - - vote_signal_enum_t eVoteSignal = CGovernanceVoting::ConvertVoteSignal(strVoteSignal); - if(eVoteSignal == VOTE_SIGNAL_NONE) { - throw JSONRPCError(RPC_INVALID_PARAMETER, - "Invalid vote signal. Please using one of the following: " - "(funding|valid|delete|endorsed)"); - } - - vote_outcome_enum_t eVoteOutcome = CGovernanceVoting::ConvertVoteOutcome(strVoteOutcome); - if(eVoteOutcome == VOTE_OUTCOME_NONE) { - throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid vote outcome. Please use one of the following: 'yes', 'no' or 'abstain'"); - } - - // EXECUTE VOTE FOR EACH MASTERNODE, COUNT SUCCESSES VS FAILURES - - int nSuccessful = 0; - int nFailed = 0; - - UniValue resultsObj(UniValue::VOBJ); - - for (const auto& mne : masternodeConfig.getEntries()) - { - // IF WE HAVE A SPECIFIC NODE REQUESTED TO VOTE, DO THAT - if(strAlias != mne.getAlias()) continue; - - // INIT OUR NEEDED VARIABLES TO EXECUTE THE VOTE - std::string strError; - std::vector vchMasterNodeSignature; - std::string strMasterNodeSignMessage; - - CPubKey pubKeyCollateralAddress; - CKey keyCollateralAddress; - CPubKey pubKeyMasternode; - CKey keyMasternode; - - // SETUP THE SIGNING KEY FROM MASTERNODE.CONF ENTRY - - UniValue statusObj(UniValue::VOBJ); - - if(!CMessageSigner::GetKeysFromSecret(mne.getPrivKey(), keyMasternode, pubKeyMasternode)) { - nFailed++; - statusObj.push_back(Pair("result", "failed")); - statusObj.push_back(Pair("errorMessage", strprintf("Invalid masternode key %s.", mne.getPrivKey()))); - resultsObj.push_back(Pair(mne.getAlias(), statusObj)); - continue; - } - - // SEARCH FOR THIS MASTERNODE ON THE NETWORK, THE NODE MUST BE ACTIVE TO VOTE - - uint256 nTxHash; - nTxHash.SetHex(mne.getTxHash()); - - int nOutputIndex = 0; - if(!ParseInt32(mne.getOutputIndex(), &nOutputIndex)) { - continue; - } - - COutPoint outpoint(nTxHash, nOutputIndex); - - CMasternode mn; - bool fMnFound = mnodeman.Get(outpoint, mn); - - if(!fMnFound) { - nFailed++; - statusObj.push_back(Pair("result", "failed")); - statusObj.push_back(Pair("errorMessage", "Masternode must be publicly available on network to vote. Masternode not found.")); - resultsObj.push_back(Pair(mne.getAlias(), statusObj)); - continue; - } - - // CREATE NEW GOVERNANCE OBJECT VOTE WITH OUTCOME/SIGNAL - - CGovernanceVote vote(outpoint, hash, eVoteSignal, eVoteOutcome); - if(!vote.Sign(keyMasternode, pubKeyMasternode)) { - nFailed++; - statusObj.push_back(Pair("result", "failed")); - statusObj.push_back(Pair("errorMessage", "Failure to sign.")); - resultsObj.push_back(Pair(mne.getAlias(), statusObj)); - continue; - } - - // UPDATE LOCAL DATABASE WITH NEW OBJECT SETTINGS - - CGovernanceException exception; - if(governance.ProcessVoteAndRelay(vote, exception, *g_connman)) { - nSuccessful++; - statusObj.push_back(Pair("result", "success")); - } - else { - nFailed++; - statusObj.push_back(Pair("result", "failed")); - statusObj.push_back(Pair("errorMessage", exception.GetMessage())); - } - - resultsObj.push_back(Pair(mne.getAlias(), statusObj)); - } - - // REPORT STATS TO THE USER - - UniValue returnObj(UniValue::VOBJ); - returnObj.push_back(Pair("overall", strprintf("Voted successfully %d time(s) and failed %d time(s).", nSuccessful, nFailed))); - returnObj.push_back(Pair("detail", resultsObj)); - - return returnObj; - } - // USERS CAN QUERY THE SYSTEM FOR A LIST OF VARIOUS GOVERNANCE ITEMS if(strCommand == "list" || strCommand == "diff") { From efe60a8c3a2f7cbe7991d5262e9514d0f491eed1 Mon Sep 17 00:00:00 2001 From: Alexander Block Date: Sat, 11 Aug 2018 21:55:56 +0200 Subject: [PATCH 038/282] Masternode related refactorings in preparation of AIP3 * Split CActiveMasternode into CActiveMasternodeInfo and CLegacyActiveMasternodeManager * Use CKeyID instead of CPubKey whenever possible in masternode code * Rename activeMasternode to activeMasternodeInfo and make it a struct * Rename pubKeyIDXXX to keyIDXXX * Bump SERIALIZATION_VERSION_STRING * Fix build error after rebase * Fix compilation warning/error with clang --- src/activemasternode.cpp | 126 +++++++++++++++++++----------------- src/activemasternode.h | 32 ++++----- src/governance-object.cpp | 22 +++---- src/governance-object.h | 4 +- src/governance-vote.cpp | 16 ++--- src/governance-vote.h | 4 +- src/init.cpp | 9 ++- src/instantx.cpp | 22 +++---- src/masternode-payments.cpp | 30 ++++----- src/masternode-payments.h | 2 +- src/masternode-sync.cpp | 2 +- src/masternode.cpp | 89 ++++++++++++------------- src/masternode.h | 32 +++++++-- src/masternodeman.cpp | 72 ++++++++++----------- src/masternodeman.h | 3 +- src/net_processing.cpp | 2 +- src/privatesend-client.cpp | 2 +- src/privatesend-server.cpp | 10 +-- src/privatesend.cpp | 28 ++++---- src/privatesend.h | 4 +- src/qt/masternodelist.cpp | 7 +- src/rpc/governance.cpp | 18 +++--- src/rpc/masternode.cpp | 30 ++++----- 23 files changed, 298 insertions(+), 268 deletions(-) diff --git a/src/activemasternode.cpp b/src/activemasternode.cpp index c16d2ee1cba3..975894a22a3c 100644 --- a/src/activemasternode.cpp +++ b/src/activemasternode.cpp @@ -11,19 +11,19 @@ #include "protocol.h" // Keep track of the active Masternode -CActiveMasternode activeMasternode; +CActiveMasternodeInfo activeMasternodeInfo; +CActiveLegacyMasternodeManager legacyActiveMasternodeManager; -void CActiveMasternode::ManageState(CConnman& connman) +void CActiveLegacyMasternodeManager::ManageState(CConnman& connman) { - LogPrint("masternode", "CActiveMasternode::ManageState -- Start\n"); + LogPrint("masternode", "CActiveLegacyMasternodeManager::ManageState -- Start\n"); if(!fMasternodeMode) { - LogPrint("masternode", "CActiveMasternode::ManageState -- Not a masternode, returning\n"); + LogPrint("masternode", "CActiveLegacyMasternodeManager::ManageState -- Not a masternode, returning\n"); return; } - if(Params().NetworkIDString() != CBaseChainParams::REGTEST && !masternodeSync.IsBlockchainSynced()) { nState = ACTIVE_MASTERNODE_SYNC_IN_PROCESS; - LogPrintf("CActiveMasternode::ManageState -- %s: %s\n", GetStateString(), GetStatus()); + LogPrintf("CActiveLegacyMasternodeManager::ManageState -- %s: %s\n", GetStateString(), GetStatus()); return; } @@ -31,7 +31,7 @@ void CActiveMasternode::ManageState(CConnman& connman) nState = ACTIVE_MASTERNODE_INITIAL; } - LogPrint("masternode", "CActiveMasternode::ManageState -- status = %s, type = %s, pinger enabled = %d\n", GetStatus(), GetTypeString(), fPingerEnabled); + LogPrint("masternode", "CActiveLegacyMasternodeManager::ManageState -- status = %s, type = %s, pinger enabled = %d\n", GetStatus(), GetTypeString(), fPingerEnabled); if(eType == MASTERNODE_UNKNOWN) { ManageStateInitial(connman); @@ -44,7 +44,7 @@ void CActiveMasternode::ManageState(CConnman& connman) SendMasternodePing(connman); } -std::string CActiveMasternode::GetStateString() const +std::string CActiveLegacyMasternodeManager::GetStateString() const { switch (nState) { case ACTIVE_MASTERNODE_INITIAL: return "INITIAL"; @@ -56,7 +56,7 @@ std::string CActiveMasternode::GetStateString() const } } -std::string CActiveMasternode::GetStatus() const +std::string CActiveLegacyMasternodeManager::GetStatus() const { switch (nState) { case ACTIVE_MASTERNODE_INITIAL: return "Node just started, not yet activated"; @@ -68,7 +68,7 @@ std::string CActiveMasternode::GetStatus() const } } -std::string CActiveMasternode::GetTypeString() const +std::string CActiveLegacyMasternodeManager::GetTypeString() const { std::string strType; switch(eType) { @@ -82,44 +82,44 @@ std::string CActiveMasternode::GetTypeString() const return strType; } -bool CActiveMasternode::SendMasternodePing(CConnman& connman) +bool CActiveLegacyMasternodeManager::SendMasternodePing(CConnman& connman) { if(!fPingerEnabled) { - LogPrint("masternode", "CActiveMasternode::SendMasternodePing -- %s: masternode ping service is disabled, skipping...\n", GetStateString()); + LogPrint("masternode", "CActiveLegacyMasternodeManager::SendMasternodePing -- %s: masternode ping service is disabled, skipping...\n", GetStateString()); return false; } - if(!mnodeman.Has(outpoint)) { + if(!mnodeman.Has(activeMasternodeInfo.outpoint)) { strNotCapableReason = "Masternode not in masternode list"; nState = ACTIVE_MASTERNODE_NOT_CAPABLE; - LogPrintf("CActiveMasternode::SendMasternodePing -- %s: %s\n", GetStateString(), strNotCapableReason); + LogPrintf("CActiveLegacyMasternodeManager::SendMasternodePing -- %s: %s\n", GetStateString(), strNotCapableReason); return false; } - CMasternodePing mnp(outpoint); + CMasternodePing mnp(activeMasternodeInfo.outpoint); mnp.nSentinelVersion = nSentinelVersion; mnp.fSentinelIsCurrent = (abs(GetAdjustedTime() - nSentinelPingTime) < MASTERNODE_SENTINEL_PING_MAX_SECONDS); - if(!mnp.Sign(keyMasternode, pubKeyMasternode)) { - LogPrintf("CActiveMasternode::SendMasternodePing -- ERROR: Couldn't sign Masternode Ping\n"); + if(!mnp.Sign(activeMasternodeInfo.keyMasternode, activeMasternodeInfo.keyIDMasternode)) { + LogPrintf("CActiveLegacyMasternodeManager::SendMasternodePing -- ERROR: Couldn't sign Masternode Ping\n"); return false; } // Update lastPing for our masternode in Masternode list - if(mnodeman.IsMasternodePingedWithin(outpoint, MASTERNODE_MIN_MNP_SECONDS, mnp.sigTime)) { - LogPrintf("CActiveMasternode::SendMasternodePing -- Too early to send Masternode Ping\n"); + if(mnodeman.IsMasternodePingedWithin(activeMasternodeInfo.outpoint, MASTERNODE_MIN_MNP_SECONDS, mnp.sigTime)) { + LogPrintf("CActiveLegacyMasternodeManager::SendMasternodePing -- Too early to send Masternode Ping\n"); return false; } - mnodeman.SetMasternodeLastPing(outpoint, mnp); + mnodeman.SetMasternodeLastPing(activeMasternodeInfo.outpoint, mnp); - LogPrintf("CActiveMasternode::SendMasternodePing -- Relaying ping, collateral=%s\n", outpoint.ToStringShort()); + LogPrintf("CActiveLegacyMasternodeManager::SendMasternodePing -- Relaying ping, collateral=%s\n", activeMasternodeInfo.outpoint.ToStringShort()); mnp.Relay(connman); return true; } -bool CActiveMasternode::UpdateSentinelPing(int version) +bool CActiveLegacyMasternodeManager::UpdateSentinelPing(int version) { nSentinelVersion = version; nSentinelPingTime = GetAdjustedTime(); @@ -127,110 +127,118 @@ bool CActiveMasternode::UpdateSentinelPing(int version) return true; } -void CActiveMasternode::ManageStateInitial(CConnman& connman) +void CActiveLegacyMasternodeManager::ManageStateInitial(CConnman& connman) { - LogPrint("masternode", "CActiveMasternode::ManageStateInitial -- status = %s, type = %s, pinger enabled = %d\n", GetStatus(), GetTypeString(), fPingerEnabled); + LogPrint("masternode", "CActiveLegacyMasternodeManager::ManageStateInitial -- status = %s, type = %s, pinger enabled = %d\n", GetStatus(), GetTypeString(), fPingerEnabled); // Check that our local network configuration is correct if (!fListen) { // listen option is probably overwritten by smth else, no good nState = ACTIVE_MASTERNODE_NOT_CAPABLE; strNotCapableReason = "Masternode must accept connections from outside. Make sure listen configuration option is not overwritten by some another parameter."; - LogPrintf("CActiveMasternode::ManageStateInitial -- %s: %s\n", GetStateString(), strNotCapableReason); + LogPrintf("CActiveLegacyMasternodeManager::ManageStateInitial -- %s: %s\n", GetStateString(), strNotCapableReason); return; } // First try to find whatever local address is specified by externalip option - bool fFoundLocal = GetLocal(service) && CMasternode::IsValidNetAddr(service); + bool fFoundLocal = GetLocal(activeMasternodeInfo.service) && CMasternode::IsValidNetAddr(activeMasternodeInfo.service); if(!fFoundLocal) { bool empty = true; // If we have some peers, let's try to find our local address from one of them connman.ForEachNodeContinueIf(CConnman::AllNodes, [&fFoundLocal, &empty, this](CNode* pnode) { empty = false; if (pnode->addr.IsIPv4()) - fFoundLocal = GetLocal(service, &pnode->addr) && CMasternode::IsValidNetAddr(service); + fFoundLocal = GetLocal(activeMasternodeInfo.service, &pnode->addr) && CMasternode::IsValidNetAddr(activeMasternodeInfo.service); return !fFoundLocal; }); // nothing and no live connections, can't do anything for now if (empty) { nState = ACTIVE_MASTERNODE_NOT_CAPABLE; strNotCapableReason = "Can't detect valid external address. Will retry when there are some connections available."; - LogPrintf("CActiveMasternode::ManageStateInitial -- %s: %s\n", GetStateString(), strNotCapableReason); + LogPrintf("CActiveLegacyMasternodeManager::ManageStateInitial -- %s: %s\n", GetStateString(), strNotCapableReason); return; } } + if (!fFoundLocal && Params().NetworkIDString() == CBaseChainParams::REGTEST) { + if (Lookup("127.0.0.1", activeMasternodeInfo.service, GetListenPort(), false)) { + fFoundLocal = true; + } + } + if(!fFoundLocal) { nState = ACTIVE_MASTERNODE_NOT_CAPABLE; strNotCapableReason = "Can't detect valid external address. Please consider using the externalip configuration option if problem persists. Make sure to use IPv4 address only."; - LogPrintf("CActiveMasternode::ManageStateInitial -- %s: %s\n", GetStateString(), strNotCapableReason); + LogPrintf("CActiveLegacyMasternodeManager::ManageStateInitial -- %s: %s\n", GetStateString(), strNotCapableReason); return; } int mainnetDefaultPort = Params(CBaseChainParams::MAIN).GetDefaultPort(); if(Params().NetworkIDString() == CBaseChainParams::MAIN) { - if(service.GetPort() != mainnetDefaultPort) { + if(activeMasternodeInfo.service.GetPort() != mainnetDefaultPort) { nState = ACTIVE_MASTERNODE_NOT_CAPABLE; - strNotCapableReason = strprintf("Invalid port: %u - only %d is supported on mainnet.", service.GetPort(), mainnetDefaultPort); - LogPrintf("CActiveMasternode::ManageStateInitial -- %s: %s\n", GetStateString(), strNotCapableReason); + strNotCapableReason = strprintf("Invalid port: %u - only %d is supported on mainnet.", activeMasternodeInfo.service.GetPort(), mainnetDefaultPort); + LogPrintf("CActiveLegacyMasternodeManager::ManageStateInitial -- %s: %s\n", GetStateString(), strNotCapableReason); return; } - } else if(service.GetPort() == mainnetDefaultPort) { + } else if(activeMasternodeInfo.service.GetPort() == mainnetDefaultPort) { nState = ACTIVE_MASTERNODE_NOT_CAPABLE; - strNotCapableReason = strprintf("Invalid port: %u - %d is only supported on mainnet.", service.GetPort(), mainnetDefaultPort); - LogPrintf("CActiveMasternode::ManageStateInitial -- %s: %s\n", GetStateString(), strNotCapableReason); + strNotCapableReason = strprintf("Invalid port: %u - %d is only supported on mainnet.", activeMasternodeInfo.service.GetPort(), mainnetDefaultPort); + LogPrintf("CActiveLegacyMasternodeManager::ManageStateInitial -- %s: %s\n", GetStateString(), strNotCapableReason); return; } - // Check socket connectivity - LogPrintf("CActiveMasternode::ManageStateInitial -- Checking inbound connection to '%s'\n", service.ToString()); - SOCKET hSocket; - bool fConnected = ConnectSocket(service, hSocket, nConnectTimeout) && IsSelectableSocket(hSocket); - CloseSocket(hSocket); + if(Params().NetworkIDString() != CBaseChainParams::REGTEST) { + // Check socket connectivity + LogPrintf("CActiveLegacyMasternodeManager::ManageStateInitial -- Checking inbound connection to '%s'\n", activeMasternodeInfo.service.ToString()); + SOCKET hSocket; + bool fConnected = ConnectSocket(activeMasternodeInfo.service, hSocket, nConnectTimeout) && IsSelectableSocket(hSocket); + CloseSocket(hSocket); - if (!fConnected) { - nState = ACTIVE_MASTERNODE_NOT_CAPABLE; - strNotCapableReason = "Could not connect to " + service.ToString(); - LogPrintf("CActiveMasternode::ManageStateInitial -- %s: %s\n", GetStateString(), strNotCapableReason); - return; + if (!fConnected) { + nState = ACTIVE_MASTERNODE_NOT_CAPABLE; + strNotCapableReason = "Could not connect to " + activeMasternodeInfo.service.ToString(); + LogPrintf("CActiveLegacyMasternodeManager::ManageStateInitial -- %s: %s\n", GetStateString(), strNotCapableReason); + return; + } } // Default to REMOTE eType = MASTERNODE_REMOTE; - LogPrint("masternode", "CActiveMasternode::ManageStateInitial -- End status = %s, type = %s, pinger enabled = %d\n", GetStatus(), GetTypeString(), fPingerEnabled); + LogPrint("masternode", "CActiveLegacyMasternodeManager::ManageStateInitial -- End status = %s, type = %s, pinger enabled = %d\n", GetStatus(), GetTypeString(), fPingerEnabled); } -void CActiveMasternode::ManageStateRemote() +void CActiveLegacyMasternodeManager::ManageStateRemote() { - LogPrint("masternode", "CActiveMasternode::ManageStateRemote -- Start status = %s, type = %s, pinger enabled = %d, pubKeyMasternode.GetID() = %s\n", - GetStatus(), GetTypeString(), fPingerEnabled, pubKeyMasternode.GetID().ToString()); + LogPrint("masternode", "CActiveLegacyMasternodeManager::ManageStateRemote -- Start status = %s, type = %s, pinger enabled = %d, keyIDMasternode = %s\n", + GetStatus(), GetTypeString(), fPingerEnabled, activeMasternodeInfo.keyIDMasternode.ToString()); - mnodeman.CheckMasternode(pubKeyMasternode, true); + mnodeman.CheckMasternode(activeMasternodeInfo.keyIDMasternode, true); masternode_info_t infoMn; - if(mnodeman.GetMasternodeInfo(pubKeyMasternode, infoMn)) { + if(mnodeman.GetMasternodeInfo(activeMasternodeInfo.keyIDMasternode, infoMn)) { if(infoMn.nProtocolVersion != PROTOCOL_VERSION) { nState = ACTIVE_MASTERNODE_NOT_CAPABLE; strNotCapableReason = "Invalid protocol version"; - LogPrintf("CActiveMasternode::ManageStateRemote -- %s: %s\n", GetStateString(), strNotCapableReason); + LogPrintf("CActiveLegacyMasternodeManager::ManageStateRemote -- %s: %s\n", GetStateString(), strNotCapableReason); return; } - if(service != infoMn.addr) { + if(activeMasternodeInfo.service != infoMn.addr) { nState = ACTIVE_MASTERNODE_NOT_CAPABLE; strNotCapableReason = "Broadcasted IP doesn't match our external address. Make sure you issued a new broadcast if IP of this masternode changed recently."; - LogPrintf("CActiveMasternode::ManageStateRemote -- %s: %s\n", GetStateString(), strNotCapableReason); + LogPrintf("CActiveLegacyMasternodeManager::ManageStateRemote -- %s: %s\n", GetStateString(), strNotCapableReason); return; } if(!CMasternode::IsValidStateForAutoStart(infoMn.nActiveState)) { nState = ACTIVE_MASTERNODE_NOT_CAPABLE; strNotCapableReason = strprintf("Masternode in %s state", CMasternode::StateToString(infoMn.nActiveState)); - LogPrintf("CActiveMasternode::ManageStateRemote -- %s: %s\n", GetStateString(), strNotCapableReason); + LogPrintf("CActiveLegacyMasternodeManager::ManageStateRemote -- %s: %s\n", GetStateString(), strNotCapableReason); return; } if(nState != ACTIVE_MASTERNODE_STARTED) { - LogPrintf("CActiveMasternode::ManageStateRemote -- STARTED!\n"); - outpoint = infoMn.outpoint; - service = infoMn.addr; + LogPrintf("CActiveLegacyMasternodeManager::ManageStateRemote -- STARTED!\n"); + activeMasternodeInfo.outpoint = infoMn.outpoint; + activeMasternodeInfo.service = infoMn.addr; fPingerEnabled = true; nState = ACTIVE_MASTERNODE_STARTED; } @@ -238,6 +246,6 @@ void CActiveMasternode::ManageStateRemote() else { nState = ACTIVE_MASTERNODE_NOT_CAPABLE; strNotCapableReason = "Masternode not in masternode list"; - LogPrintf("CActiveMasternode::ManageStateRemote -- %s: %s\n", GetStateString(), strNotCapableReason); + LogPrintf("CActiveLegacyMasternodeManager::ManageStateRemote -- %s: %s\n", GetStateString(), strNotCapableReason); } } diff --git a/src/activemasternode.h b/src/activemasternode.h index 30583d524abf..7920fce382eb 100644 --- a/src/activemasternode.h +++ b/src/activemasternode.h @@ -11,7 +11,8 @@ #include "net.h" #include "primitives/transaction.h" -class CActiveMasternode; +struct CActiveMasternodeInfo; +class CActiveLegacyMasternodeManager; static const int ACTIVE_MASTERNODE_INITIAL = 0; // initial state static const int ACTIVE_MASTERNODE_SYNC_IN_PROCESS = 1; @@ -19,10 +20,21 @@ static const int ACTIVE_MASTERNODE_INPUT_TOO_NEW = 2; static const int ACTIVE_MASTERNODE_NOT_CAPABLE = 3; static const int ACTIVE_MASTERNODE_STARTED = 4; -extern CActiveMasternode activeMasternode; +extern CActiveMasternodeInfo activeMasternodeInfo; +extern CActiveLegacyMasternodeManager legacyActiveMasternodeManager; + +struct CActiveMasternodeInfo { + // Keys for the active Masternode + CKeyID keyIDMasternode; + CKey keyMasternode; + + // Initialized while registering Masternode + COutPoint outpoint; + CService service; +}; // Responsible for activating the Masternode and pinging the network -class CActiveMasternode +class CActiveLegacyMasternodeManager { public: enum masternode_type_enum_t { @@ -46,25 +58,13 @@ class CActiveMasternode uint32_t nSentinelVersion; public: - // Keys for the active Masternode - CPubKey pubKeyMasternode; - CKey keyMasternode; - - // Initialized while registering Masternode - COutPoint outpoint; - CService service; - int nState; // should be one of ACTIVE_MASTERNODE_XXXX std::string strNotCapableReason; - CActiveMasternode() + CActiveLegacyMasternodeManager() : eType(MASTERNODE_UNKNOWN), fPingerEnabled(false), - pubKeyMasternode(), - keyMasternode(), - outpoint(), - service(), nState(ACTIVE_MASTERNODE_INITIAL) {} diff --git a/src/governance-object.cpp b/src/governance-object.cpp index 4cf8db157fef..12cd848a96d5 100644 --- a/src/governance-object.cpp +++ b/src/governance-object.cpp @@ -265,7 +265,7 @@ void CGovernanceObject::SetMasternodeOutpoint(const COutPoint& outpoint) masternodeOutpoint = outpoint; } -bool CGovernanceObject::Sign(const CKey& keyMasternode, const CPubKey& pubKeyMasternode) +bool CGovernanceObject::Sign(const CKey& keyMasternode, const CKeyID& keyIDMasternode) { std::string strError; @@ -277,7 +277,7 @@ bool CGovernanceObject::Sign(const CKey& keyMasternode, const CPubKey& pubKeyMas return false; } - if (!CHashSigner::VerifyHash(hash, pubKeyMasternode, vchSig, strError)) { + if (!CHashSigner::VerifyHash(hash, keyIDMasternode, vchSig, strError)) { LogPrintf("CGovernanceObject::Sign -- VerifyHash() failed, error: %s\n", strError); return false; } @@ -288,30 +288,30 @@ bool CGovernanceObject::Sign(const CKey& keyMasternode, const CPubKey& pubKeyMas return false; } - if (!CMessageSigner::VerifyMessage(pubKeyMasternode, vchSig, strMessage, strError)) { + if(!CMessageSigner::VerifyMessage(keyIDMasternode, vchSig, strMessage, strError)) { LogPrintf("CGovernanceObject::Sign -- VerifyMessage() failed, error: %s\n", strError); return false; } } LogPrint("gobject", "CGovernanceObject::Sign -- pubkey id = %s, masternode = %s\n", - pubKeyMasternode.GetID().ToString(), masternodeOutpoint.ToStringShort()); + keyIDMasternode.ToString(), masternodeOutpoint.ToStringShort()); return true; } -bool CGovernanceObject::CheckSignature(const CPubKey& pubKeyMasternode) const +bool CGovernanceObject::CheckSignature(const CKeyID& keyIDMasternode) const { std::string strError; if (sporkManager.IsSporkActive(SPORK_6_NEW_SIGS)) { uint256 hash = GetSignatureHash(); - if (!CHashSigner::VerifyHash(hash, pubKeyMasternode, vchSig, strError)) { + if (!CHashSigner::VerifyHash(hash, keyIDMasternode, vchSig, strError)) { // could be an old object std::string strMessage = GetSignatureMessage(); - if (!CMessageSigner::VerifyMessage(pubKeyMasternode, vchSig, strMessage, strError)) { + if(!CMessageSigner::VerifyMessage(keyIDMasternode, vchSig, strMessage, strError)) { // nope, not in old format either LogPrintf("CGovernance::CheckSignature -- VerifyMessage() failed, error: %s\n", strError); return false; @@ -320,7 +320,7 @@ bool CGovernanceObject::CheckSignature(const CPubKey& pubKeyMasternode) const } else { std::string strMessage = GetSignatureMessage(); - if (!CMessageSigner::VerifyMessage(pubKeyMasternode, vchSig, strMessage, strError)) { + if (!CMessageSigner::VerifyMessage(keyIDMasternode, vchSig, strMessage, strError)) { LogPrintf("CGovernance::CheckSignature -- VerifyMessage() failed, error: %s\n", strError); return false; } @@ -490,7 +490,7 @@ bool CGovernanceObject::IsValidLocally(std::string& strError, bool& fMissingMast masternode_info_t infoMn; if (!mnodeman.GetMasternodeInfo(masternodeOutpoint, infoMn)) { - CMasternode::CollateralStatus err = CMasternode::CheckCollateral(masternodeOutpoint, CPubKey()); + CMasternode::CollateralStatus err = CMasternode::CheckCollateral(masternodeOutpoint, CKeyID()); if (err == CMasternode::COLLATERAL_UTXO_NOT_FOUND) { strError = "Failed to find Masternode UTXO, missing masternode=" + strOutpoint + "\n"; } else if (err == CMasternode::COLLATERAL_INVALID_AMOUNT) { @@ -507,8 +507,8 @@ bool CGovernanceObject::IsValidLocally(std::string& strError, bool& fMissingMast } // Check that we have a valid MN signature - if (!CheckSignature(infoMn.pubKeyMasternode)) { - strError = "Invalid masternode signature for: " + strOutpoint + ", pubkey id = " + infoMn.pubKeyMasternode.GetID().ToString(); + if (!CheckSignature(infoMn.keyIDMasternode)) { + strError = "Invalid masternode signature for: " + strOutpoint + ", pubkey id = " + infoMn.keyIDMasternode.ToString(); return false; } diff --git a/src/governance-object.h b/src/governance-object.h index 2ebfa010c87c..43c4a23ca7b5 100644 --- a/src/governance-object.h +++ b/src/governance-object.h @@ -252,8 +252,8 @@ class CGovernanceObject // Signature related functions void SetMasternodeOutpoint(const COutPoint& outpoint); - bool Sign(const CKey& keyMasternode, const CPubKey& pubKeyMasternode); - bool CheckSignature(const CPubKey& pubKeyMasternode) const; + bool Sign(const CKey& keyMasternode, const CKeyID& keyIDMasternode); + bool CheckSignature(const CKeyID& keyIDMasternode) const; std::string GetSignatureMessage() const; uint256 GetSignatureHash() const; diff --git a/src/governance-vote.cpp b/src/governance-vote.cpp index 2707c0341b64..1c8b215fb103 100644 --- a/src/governance-vote.cpp +++ b/src/governance-vote.cpp @@ -155,7 +155,7 @@ uint256 CGovernanceVote::GetSignatureHash() const return SerializeHash(*this); } -bool CGovernanceVote::Sign(const CKey& keyMasternode, const CPubKey& pubKeyMasternode) +bool CGovernanceVote::Sign(const CKey& keyMasternode, const CKeyID& keyIDMasternode) { std::string strError; @@ -167,7 +167,7 @@ bool CGovernanceVote::Sign(const CKey& keyMasternode, const CPubKey& pubKeyMaste return false; } - if (!CHashSigner::VerifyHash(hash, pubKeyMasternode, vchSig, strError)) { + if (!CHashSigner::VerifyHash(hash, keyIDMasternode, vchSig, strError)) { LogPrintf("CGovernanceVote::Sign -- VerifyHash() failed, error: %s\n", strError); return false; } @@ -181,7 +181,7 @@ bool CGovernanceVote::Sign(const CKey& keyMasternode, const CPubKey& pubKeyMaste return false; } - if(!CMessageSigner::VerifyMessage(pubKeyMasternode, vchSig, strMessage, strError)) { + if(!CMessageSigner::VerifyMessage(keyIDMasternode, vchSig, strMessage, strError)) { LogPrintf("CGovernanceVote::Sign -- VerifyMessage() failed, error: %s\n", strError); return false; } @@ -190,21 +190,21 @@ bool CGovernanceVote::Sign(const CKey& keyMasternode, const CPubKey& pubKeyMaste return true; } -bool CGovernanceVote::CheckSignature(const CPubKey& pubKeyMasternode) const +bool CGovernanceVote::CheckSignature(const CKeyID& keyIDMasternode) const { std::string strError; if (sporkManager.IsSporkActive(SPORK_6_NEW_SIGS)) { uint256 hash = GetSignatureHash(); - if (!CHashSigner::VerifyHash(hash, pubKeyMasternode, vchSig, strError)) { + if (!CHashSigner::VerifyHash(hash, keyIDMasternode, vchSig, strError)) { // could be a signature in old format std::string strMessage = masternodeOutpoint.ToStringShort() + "|" + nParentHash.ToString() + "|" + boost::lexical_cast(nVoteSignal) + "|" + boost::lexical_cast(nVoteOutcome) + "|" + boost::lexical_cast(nTime); - if(!CMessageSigner::VerifyMessage(pubKeyMasternode, vchSig, strMessage, strError)) { + if(!CMessageSigner::VerifyMessage(keyIDMasternode, vchSig, strMessage, strError)) { // nope, not in old format either LogPrint("gobject", "CGovernanceVote::IsValid -- VerifyMessage() failed, error: %s\n", strError); return false; @@ -216,7 +216,7 @@ bool CGovernanceVote::CheckSignature(const CPubKey& pubKeyMasternode) const boost::lexical_cast(nVoteOutcome) + "|" + boost::lexical_cast(nTime); - if(!CMessageSigner::VerifyMessage(pubKeyMasternode, vchSig, strMessage, strError)) { + if(!CMessageSigner::VerifyMessage(keyIDMasternode, vchSig, strMessage, strError)) { LogPrint("gobject", "CGovernanceVote::IsValid -- VerifyMessage() failed, error: %s\n", strError); return false; } @@ -254,7 +254,7 @@ bool CGovernanceVote::IsValid(bool fSignatureCheck) const if(!fSignatureCheck) return true; - return CheckSignature(infoMn.pubKeyMasternode); + return CheckSignature(infoMn.keyIDMasternode); } bool operator==(const CGovernanceVote& vote1, const CGovernanceVote& vote2) diff --git a/src/governance-vote.h b/src/governance-vote.h index 68772503cd01..a6bbc7947c36 100644 --- a/src/governance-vote.h +++ b/src/governance-vote.h @@ -93,8 +93,8 @@ class CGovernanceVote void SetSignature(const std::vector& vchSigIn) { vchSig = vchSigIn; } - bool Sign(const CKey& keyMasternode, const CPubKey& pubKeyMasternode); - bool CheckSignature(const CPubKey& pubKeyMasternode) const; + bool Sign(const CKey& keyMasternode, const CKeyID& keyIDMasternode); + bool CheckSignature(const CKeyID& keyIDMasternode) const; bool IsValid(bool fSignatureCheck) const; void Relay(CConnman& connman) const; diff --git a/src/init.cpp b/src/init.cpp index a3c459eb4b51..e9571e093497 100644 --- a/src/init.cpp +++ b/src/init.cpp @@ -1818,10 +1818,13 @@ bool AppInitMain(boost::thread_group& threadGroup, CScheduler& scheduler) std::string strMasterNodePrivKey = GetArg("-masternodeprivkey", ""); if(!strMasterNodePrivKey.empty()) { - if(!CMessageSigner::GetKeysFromSecret(strMasterNodePrivKey, activeMasternode.keyMasternode, activeMasternode.pubKeyMasternode)) + CPubKey pubKeyMasternode; + if(!CMessageSigner::GetKeysFromSecret(strMasterNodePrivKey, activeMasternodeInfo.keyMasternode, pubKeyMasternode)) return InitError(_("Invalid masternodeprivkey. Please see documenation.")); - LogPrintf(" pubKeyMasternode: %s\n", CBitcoinAddress(activeMasternode.pubKeyMasternode.GetID()).ToString()); + activeMasternodeInfo.keyIDMasternode = pubKeyMasternode.GetID(); + + LogPrintf(" keyIDMasternode: %s\n", CBitcoinAddress(activeMasternodeInfo.keyIDMasternode).ToString()); } else { return InitError(_("You must specify a masternodeprivkey in the configuration. Please see documentation for help.")); } @@ -1940,7 +1943,7 @@ bool AppInitMain(boost::thread_group& threadGroup, CScheduler& scheduler) scheduler.scheduleEvery(boost::bind(&CNetFulfilledRequestManager::DoMaintenance, boost::ref(netfulfilledman)), 60); scheduler.scheduleEvery(boost::bind(&CMasternodeSync::DoMaintenance, boost::ref(masternodeSync), boost::ref(*g_connman)), MASTERNODE_SYNC_TICK_SECONDS); scheduler.scheduleEvery(boost::bind(&CMasternodeMan::DoMaintenance, boost::ref(mnodeman), boost::ref(*g_connman)), 1); - scheduler.scheduleEvery(boost::bind(&CActiveMasternode::DoMaintenance, boost::ref(activeMasternode), boost::ref(*g_connman)), MASTERNODE_MIN_MNP_SECONDS); + scheduler.scheduleEvery(boost::bind(&CActiveLegacyMasternodeManager::DoMaintenance, boost::ref(legacyActiveMasternodeManager), boost::ref(*g_connman)), MASTERNODE_MIN_MNP_SECONDS); scheduler.scheduleEvery(boost::bind(&CMasternodePayments::DoMaintenance, boost::ref(mnpayments)), 60); scheduler.scheduleEvery(boost::bind(&CGovernanceManager::DoMaintenance, boost::ref(governance), boost::ref(*g_connman)), 60 * 5); diff --git a/src/instantx.cpp b/src/instantx.cpp index a82f45993e5e..7f46962fbacd 100644 --- a/src/instantx.cpp +++ b/src/instantx.cpp @@ -234,8 +234,8 @@ void CInstantSend::Vote(CTxLockCandidate& txLockCandidate, CConnman& connman) int nRank; int nMinRequiredProtocol = std::max(MIN_INSTANTSEND_PROTO_VERSION, mnpayments.GetMinMasternodePaymentsProto()); - if(!mnodeman.GetMasternodeRank(activeMasternode.outpoint, nRank, nLockInputHeight, nMinRequiredProtocol)) { - LogPrint("instantsend", "CInstantSend::Vote -- Can't calculate rank for masternode %s\n", activeMasternode.outpoint.ToStringShort()); + if(!mnodeman.GetMasternodeRank(activeMasternodeInfo.outpoint, nRank, nLockInputHeight, nMinRequiredProtocol)) { + LogPrint("instantsend", "CInstantSend::Vote -- Can't calculate rank for masternode %s\n", activeMasternodeInfo.outpoint.ToStringShort()); continue; } @@ -255,7 +255,7 @@ void CInstantSend::Vote(CTxLockCandidate& txLockCandidate, CConnman& connman) if(itVoted != mapVotedOutpoints.end()) { for (const auto& hash : itVoted->second) { std::map::iterator it2 = mapTxLockCandidates.find(hash); - if(it2->second.HasMasternodeVoted(outpointLockPair.first, activeMasternode.outpoint)) { + if(it2->second.HasMasternodeVoted(outpointLockPair.first, activeMasternodeInfo.outpoint)) { // we already voted for this outpoint to be included either in the same tx or in a competing one, // skip it anyway fAlreadyVoted = true; @@ -270,7 +270,7 @@ void CInstantSend::Vote(CTxLockCandidate& txLockCandidate, CConnman& connman) } // we haven't voted for this outpoint yet, let's try to do this now - CTxLockVote vote(txHash, outpointLockPair.first, activeMasternode.outpoint); + CTxLockVote vote(txHash, outpointLockPair.first, activeMasternodeInfo.outpoint); if(!vote.Sign()) { LogPrintf("CInstantSend::Vote -- Failed to sign consensus vote\n"); @@ -1060,10 +1060,10 @@ bool CTxLockVote::CheckSignature() const if (sporkManager.IsSporkActive(SPORK_6_NEW_SIGS)) { uint256 hash = GetSignatureHash(); - if (!CHashSigner::VerifyHash(hash, infoMn.pubKeyMasternode, vchMasternodeSignature, strError)) { + if (!CHashSigner::VerifyHash(hash, infoMn.keyIDMasternode, vchMasternodeSignature, strError)) { // could be a signature in old format std::string strMessage = txHash.ToString() + outpoint.ToStringShort(); - if(!CMessageSigner::VerifyMessage(infoMn.pubKeyMasternode, vchMasternodeSignature, strMessage, strError)) { + if(!CMessageSigner::VerifyMessage(infoMn.keyIDMasternode, vchMasternodeSignature, strMessage, strError)) { // nope, not in old format either LogPrintf("CTxLockVote::CheckSignature -- VerifyMessage() failed, error: %s\n", strError); return false; @@ -1071,7 +1071,7 @@ bool CTxLockVote::CheckSignature() const } } else { std::string strMessage = txHash.ToString() + outpoint.ToStringShort(); - if(!CMessageSigner::VerifyMessage(infoMn.pubKeyMasternode, vchMasternodeSignature, strMessage, strError)) { + if(!CMessageSigner::VerifyMessage(infoMn.keyIDMasternode, vchMasternodeSignature, strMessage, strError)) { LogPrintf("CTxLockVote::CheckSignature -- VerifyMessage() failed, error: %s\n", strError); return false; } @@ -1087,24 +1087,24 @@ bool CTxLockVote::Sign() if (sporkManager.IsSporkActive(SPORK_6_NEW_SIGS)) { uint256 hash = GetSignatureHash(); - if(!CHashSigner::SignHash(hash, activeMasternode.keyMasternode, vchMasternodeSignature)) { + if(!CHashSigner::SignHash(hash, activeMasternodeInfo.keyMasternode, vchMasternodeSignature)) { LogPrintf("CTxLockVote::Sign -- SignHash() failed\n"); return false; } - if (!CHashSigner::VerifyHash(hash, activeMasternode.pubKeyMasternode, vchMasternodeSignature, strError)) { + if (!CHashSigner::VerifyHash(hash, activeMasternodeInfo.keyIDMasternode, vchMasternodeSignature, strError)) { LogPrintf("CTxLockVote::Sign -- VerifyHash() failed, error: %s\n", strError); return false; } } else { std::string strMessage = txHash.ToString() + outpoint.ToStringShort(); - if(!CMessageSigner::SignMessage(strMessage, vchMasternodeSignature, activeMasternode.keyMasternode)) { + if(!CMessageSigner::SignMessage(strMessage, vchMasternodeSignature, activeMasternodeInfo.keyMasternode)) { LogPrintf("CTxLockVote::Sign -- SignMessage() failed\n"); return false; } - if(!CMessageSigner::VerifyMessage(activeMasternode.pubKeyMasternode, vchMasternodeSignature, strMessage, strError)) { + if(!CMessageSigner::VerifyMessage(activeMasternodeInfo.keyIDMasternode, vchMasternodeSignature, strMessage, strError)) { LogPrintf("CTxLockVote::Sign -- VerifyMessage() failed, error: %s\n", strError); return false; } diff --git a/src/masternode-payments.cpp b/src/masternode-payments.cpp index 858841b4fca1..8f6c44319a7d 100644 --- a/src/masternode-payments.cpp +++ b/src/masternode-payments.cpp @@ -265,7 +265,7 @@ void CMasternodePayments::FillBlockPayee(CMutableTransaction& txNew, int nBlockH return; } // fill payee with locally calculated winner and hope for the best - payee = GetScriptForDestination(mnInfo.pubKeyCollateralAddress.GetID()); + payee = GetScriptForDestination(mnInfo.keyIDCollateralAddress); } // GET MASTERNODE PAYMENT VARIABLES SETUP @@ -385,7 +385,7 @@ void CMasternodePayments::ProcessMessage(CNode* pfrom, const std::string& strCom } int nDos = 0; - if(!vote.CheckSignature(mnInfo.pubKeyMasternode, nCachedBlockHeight, nDos)) { + if(!vote.CheckSignature(mnInfo.keyIDMasternode, nCachedBlockHeight, nDos)) { if(nDos) { LOCK(cs_main); LogPrintf("MASTERNODEPAYMENTVOTE -- ERROR: invalid signature\n"); @@ -445,12 +445,12 @@ bool CMasternodePaymentVote::Sign() if (sporkManager.IsSporkActive(SPORK_6_NEW_SIGS)) { uint256 hash = GetSignatureHash(); - if(!CHashSigner::SignHash(hash, activeMasternode.keyMasternode, vchSig)) { + if(!CHashSigner::SignHash(hash, activeMasternodeInfo.keyMasternode, vchSig)) { LogPrintf("CMasternodePaymentVote::Sign -- SignHash() failed\n"); return false; } - if (!CHashSigner::VerifyHash(hash, activeMasternode.pubKeyMasternode, vchSig, strError)) { + if (!CHashSigner::VerifyHash(hash, activeMasternodeInfo.keyIDMasternode, vchSig, strError)) { LogPrintf("CMasternodePaymentVote::Sign -- VerifyHash() failed, error: %s\n", strError); return false; } @@ -459,12 +459,12 @@ bool CMasternodePaymentVote::Sign() boost::lexical_cast(nBlockHeight) + ScriptToAsmStr(payee); - if(!CMessageSigner::SignMessage(strMessage, vchSig, activeMasternode.keyMasternode)) { + if(!CMessageSigner::SignMessage(strMessage, vchSig, activeMasternodeInfo.keyMasternode)) { LogPrintf("CMasternodePaymentVote::Sign -- SignMessage() failed\n"); return false; } - if(!CMessageSigner::VerifyMessage(activeMasternode.pubKeyMasternode, vchSig, strMessage, strError)) { + if(!CMessageSigner::VerifyMessage(activeMasternodeInfo.keyIDMasternode, vchSig, strMessage, strError)) { LogPrintf("CMasternodePaymentVote::Sign -- VerifyMessage() failed, error: %s\n", strError); return false; } @@ -490,7 +490,7 @@ bool CMasternodePayments::IsScheduled(const masternode_info_t& mnInfo, int nNotB if(!masternodeSync.IsMasternodeListSynced()) return false; CScript mnpayee; - mnpayee = GetScriptForDestination(mnInfo.pubKeyCollateralAddress.GetID()); + mnpayee = GetScriptForDestination(mnInfo.keyIDCollateralAddress); CScript payee; for(int64_t h = nCachedBlockHeight; h <= nCachedBlockHeight + 8; h++){ @@ -760,7 +760,7 @@ bool CMasternodePayments::ProcessBlock(int nBlockHeight, CConnman& connman) int nRank; - if (!mnodeman.GetMasternodeRank(activeMasternode.outpoint, nRank, nBlockHeight - 101, GetMinMasternodePaymentsProto())) { + if (!mnodeman.GetMasternodeRank(activeMasternodeInfo.outpoint, nRank, nBlockHeight - 101, GetMinMasternodePaymentsProto())) { LogPrint("mnpayments", "CMasternodePayments::ProcessBlock -- Unknown Masternode\n"); return false; } @@ -773,7 +773,7 @@ bool CMasternodePayments::ProcessBlock(int nBlockHeight, CConnman& connman) // LOCATE THE NEXT MASTERNODE WHICH SHOULD BE PAID - LogPrintf("CMasternodePayments::ProcessBlock -- Start: nBlockHeight=%d, masternode=%s\n", nBlockHeight, activeMasternode.outpoint.ToStringShort()); + LogPrintf("CMasternodePayments::ProcessBlock -- Start: nBlockHeight=%d, masternode=%s\n", nBlockHeight, activeMasternodeInfo.outpoint.ToStringShort()); // pay to the oldest MN that still had no payment but its input is old enough and it was active long enough int nCount = 0; @@ -787,9 +787,9 @@ bool CMasternodePayments::ProcessBlock(int nBlockHeight, CConnman& connman) LogPrintf("CMasternodePayments::ProcessBlock -- Masternode found by GetNextMasternodeInQueueForPayment(): %s\n", mnInfo.outpoint.ToStringShort()); - CScript payee = GetScriptForDestination(mnInfo.pubKeyCollateralAddress.GetID()); + CScript payee = GetScriptForDestination(mnInfo.keyIDCollateralAddress); - CMasternodePaymentVote voteNew(activeMasternode.outpoint, nBlockHeight, payee); + CMasternodePaymentVote voteNew(activeMasternodeInfo.outpoint, nBlockHeight, payee); CTxDestination address1; ExtractDestination(payee, address1); @@ -894,7 +894,7 @@ void CMasternodePaymentVote::Relay(CConnman& connman) const connman.RelayInv(inv); } -bool CMasternodePaymentVote::CheckSignature(const CPubKey& pubKeyMasternode, int nValidationHeight, int &nDos) const +bool CMasternodePaymentVote::CheckSignature(const CKeyID& keyIDMasternode, int nValidationHeight, int &nDos) const { // do not ban by default nDos = 0; @@ -903,12 +903,12 @@ bool CMasternodePaymentVote::CheckSignature(const CPubKey& pubKeyMasternode, int if (sporkManager.IsSporkActive(SPORK_6_NEW_SIGS)) { uint256 hash = GetSignatureHash(); - if (!CHashSigner::VerifyHash(hash, pubKeyMasternode, vchSig, strError)) { + if (!CHashSigner::VerifyHash(hash, keyIDMasternode, vchSig, strError)) { // could be a signature in old format std::string strMessage = masternodeOutpoint.ToStringShort() + boost::lexical_cast(nBlockHeight) + ScriptToAsmStr(payee); - if(!CMessageSigner::VerifyMessage(pubKeyMasternode, vchSig, strMessage, strError)) { + if(!CMessageSigner::VerifyMessage(keyIDMasternode, vchSig, strMessage, strError)) { // nope, not in old format either // Only ban for future block vote when we are already synced. // Otherwise it could be the case when MN which signed this vote is using another key now @@ -925,7 +925,7 @@ bool CMasternodePaymentVote::CheckSignature(const CPubKey& pubKeyMasternode, int boost::lexical_cast(nBlockHeight) + ScriptToAsmStr(payee); - if (!CMessageSigner::VerifyMessage(pubKeyMasternode, vchSig, strMessage, strError)) { + if (!CMessageSigner::VerifyMessage(keyIDMasternode, vchSig, strMessage, strError)) { // Only ban for future block vote when we are already synced. // Otherwise it could be the case when MN which signed this vote is using another key now // and we have no idea about the old one. diff --git a/src/masternode-payments.h b/src/masternode-payments.h index 3dc743875934..48ea3737a4da 100644 --- a/src/masternode-payments.h +++ b/src/masternode-payments.h @@ -160,7 +160,7 @@ class CMasternodePaymentVote uint256 GetSignatureHash() const; bool Sign(); - bool CheckSignature(const CPubKey& pubKeyMasternode, int nValidationHeight, int &nDos) const; + bool CheckSignature(const CKeyID& keyIDMasternode, int nValidationHeight, int &nDos) const; bool IsValid(CNode* pnode, int nValidationHeight, std::string& strError, CConnman& connman) const; void Relay(CConnman& connman) const; diff --git a/src/masternode-sync.cpp b/src/masternode-sync.cpp index cda2f067dcd6..be5c475e590f 100644 --- a/src/masternode-sync.cpp +++ b/src/masternode-sync.cpp @@ -88,7 +88,7 @@ void CMasternodeSync::SwitchToNextAsset(CConnman& connman) nRequestedMasternodeAssets = MASTERNODE_SYNC_FINISHED; uiInterface.NotifyAdditionalDataSyncProgressChanged(1); //try to activate our masternode if possible - activeMasternode.ManageState(connman); + legacyActiveMasternodeManager.ManageState(connman); connman.ForEachNode(CConnman::AllNodes, [](CNode* pnode) { netfulfilledman.AddFulfilledRequest(pnode->addr, "full-sync"); diff --git a/src/masternode.cpp b/src/masternode.cpp index 4296b48debd9..e20c3159a7df 100644 --- a/src/masternode.cpp +++ b/src/masternode.cpp @@ -27,9 +27,9 @@ CMasternode::CMasternode() : fAllowMixingTx(true) {} -CMasternode::CMasternode(CService addr, COutPoint outpoint, CPubKey pubKeyCollateralAddress, CPubKey pubKeyMasternode, int nProtocolVersionIn) : +CMasternode::CMasternode(CService addr, COutPoint outpoint, CPubKey pubKeyCollateralAddressNew, CPubKey pubKeyMasternodeNew, int nProtocolVersionIn) : masternode_info_t{ MASTERNODE_ENABLED, nProtocolVersionIn, GetAdjustedTime(), - outpoint, addr, pubKeyCollateralAddress, pubKeyMasternode}, + outpoint, addr, pubKeyCollateralAddressNew, pubKeyMasternodeNew}, fAllowMixingTx(true) {} @@ -61,6 +61,7 @@ bool CMasternode::UpdateFromNewBroadcast(CMasternodeBroadcast& mnb, CConnman& co if(mnb.sigTime <= sigTime && !mnb.fRecovery) return false; pubKeyMasternode = mnb.pubKeyMasternode; + keyIDMasternode = mnb.pubKeyMasternode.GetID(); sigTime = mnb.sigTime; vchSig = mnb.vchSig; nProtocolVersion = mnb.nProtocolVersion; @@ -74,11 +75,11 @@ bool CMasternode::UpdateFromNewBroadcast(CMasternodeBroadcast& mnb, CConnman& co mnodeman.mapSeenMasternodePing.insert(std::make_pair(lastPing.GetHash(), lastPing)); } // if it matches our Masternode privkey... - if(fMasternodeMode && pubKeyMasternode == activeMasternode.pubKeyMasternode) { + if(fMasternodeMode && keyIDMasternode == activeMasternodeInfo.keyIDMasternode) { nPoSeBanScore = -MASTERNODE_POSE_BAN_MAX_SCORE; if(nProtocolVersion == PROTOCOL_VERSION) { // ... and PROTOCOL_VERSION, then we've been remotely activated ... - activeMasternode.ManageState(connman); + legacyActiveMasternodeManager.ManageState(connman); } else { // ... otherwise we need to reactivate our node, do not add it to the list and do not relay // but also do not ban the node we get this message from @@ -102,13 +103,13 @@ arith_uint256 CMasternode::CalculateScore(const uint256& blockHash) const return UintToArith256(ss.GetHash()); } -CMasternode::CollateralStatus CMasternode::CheckCollateral(const COutPoint& outpoint, const CPubKey& pubkey) +CMasternode::CollateralStatus CMasternode::CheckCollateral(const COutPoint& outpoint, const CKeyID& keyID) { int nHeight; - return CheckCollateral(outpoint, pubkey, nHeight); + return CheckCollateral(outpoint, keyID, nHeight); } -CMasternode::CollateralStatus CMasternode::CheckCollateral(const COutPoint& outpoint, const CPubKey& pubkey, int& nHeightRet) +CMasternode::CollateralStatus CMasternode::CheckCollateral(const COutPoint& outpoint, const CKeyID& keyID, int& nHeightRet) { AssertLockHeld(cs_main); @@ -121,7 +122,7 @@ CMasternode::CollateralStatus CMasternode::CheckCollateral(const COutPoint& outp return COLLATERAL_INVALID_AMOUNT; } - if(pubkey == CPubKey() || coin.out.scriptPubKey != GetScriptForDestination(pubkey.GetID())) { + if(keyID.IsNull() || coin.out.scriptPubKey != GetScriptForDestination(keyID)) { return COLLATERAL_INVALID_PUBKEY; } nHeightRet = coin.nHeight; @@ -171,7 +172,7 @@ void CMasternode::Check(bool fForce) } int nActiveStatePrev = nActiveState; - bool fOurMasternode = fMasternodeMode && activeMasternode.pubKeyMasternode == pubKeyMasternode; + bool fOurMasternode = fMasternodeMode && activeMasternodeInfo.keyIDMasternode == keyIDMasternode; // masternode doesn't meet payment protocol requirements ... bool fRequireUpdate = nProtocolVersion < mnpayments.GetMinMasternodePaymentsProto() || @@ -319,7 +320,7 @@ void CMasternode::UpdateLastPaid(const CBlockIndex *pindex, int nMaxBlocksToScan const CBlockIndex *BlockReading = pindex; - CScript mnpayee = GetScriptForDestination(pubKeyCollateralAddress.GetID()); + CScript mnpayee = GetScriptForDestination(keyIDCollateralAddress); // LogPrint("mnpayments", "CMasternode::UpdateLastPaidBlock -- searching for block with payment to %s\n", outpoint.ToStringShort()); LOCK(cs_mapMasternodeBlocks); @@ -396,7 +397,7 @@ bool CMasternodeBroadcast::Create(const COutPoint& outpoint, const CService& ser // wait for reindex and/or import to finish if (fImporting || fReindex) return false; - LogPrint("masternode", "CMasternodeBroadcast::Create -- pubKeyCollateralAddressNew = %s, pubKeyMasternodeNew.GetID() = %s\n", + LogPrint("masternode", "CMasternodeBroadcast::Create -- pubKeyCollateralAddressNew = %s, keyIDMasternode = %s\n", CBitcoinAddress(pubKeyCollateralAddressNew.GetID()).ToString(), pubKeyMasternodeNew.GetID().ToString()); @@ -409,7 +410,7 @@ bool CMasternodeBroadcast::Create(const COutPoint& outpoint, const CService& ser }; CMasternodePing mnp(outpoint); - if (!mnp.Sign(keyMasternodeNew, pubKeyMasternodeNew)) + if (!mnp.Sign(keyMasternodeNew, pubKeyMasternodeNew.GetID())) return Log(strprintf("Failed to sign ping, masternode=%s", outpoint.ToStringShort())); mnbRet = CMasternodeBroadcast(service, outpoint, pubKeyCollateralAddressNew, pubKeyMasternodeNew, PROTOCOL_VERSION); @@ -457,19 +458,19 @@ bool CMasternodeBroadcast::SimpleCheck(int& nDos) } CScript pubkeyScript; - pubkeyScript = GetScriptForDestination(pubKeyCollateralAddress.GetID()); + pubkeyScript = GetScriptForDestination(keyIDCollateralAddress); if(pubkeyScript.size() != 25) { - LogPrintf("CMasternodeBroadcast::SimpleCheck -- pubKeyCollateralAddress has the wrong size\n"); + LogPrintf("CMasternodeBroadcast::SimpleCheck -- keyIDCollateralAddress has the wrong size\n"); nDos = 100; return false; } CScript pubkeyScript2; - pubkeyScript2 = GetScriptForDestination(pubKeyMasternode.GetID()); + pubkeyScript2 = GetScriptForDestination(keyIDMasternode); if(pubkeyScript2.size() != 25) { - LogPrintf("CMasternodeBroadcast::SimpleCheck -- pubKeyMasternode has the wrong size\n"); + LogPrintf("CMasternodeBroadcast::SimpleCheck -- keyIDMasternode has the wrong size\n"); nDos = 100; return false; } @@ -511,8 +512,8 @@ bool CMasternodeBroadcast::Update(CMasternode* pmn, int& nDos, CConnman& connman } // IsVnAssociatedWithPubkey is validated once in CheckOutpoint, after that they just need to match - if(pmn->pubKeyCollateralAddress != pubKeyCollateralAddress) { - LogPrintf("CMasternodeBroadcast::Update -- Got mismatched pubKeyCollateralAddress and outpoint\n"); + if(pmn->keyIDCollateralAddress != keyIDCollateralAddress) { + LogPrintf("CMasternodeBroadcast::Update -- Got mismatched keyIDCollateralAddress and outpoint\n"); nDos = 33; return false; } @@ -523,7 +524,7 @@ bool CMasternodeBroadcast::Update(CMasternode* pmn, int& nDos, CConnman& connman } // if ther was no masternode broadcast recently or if it matches our Masternode privkey... - if(!pmn->IsBroadcastedWithin(MASTERNODE_MIN_MNB_SECONDS) || (fMasternodeMode && pubKeyMasternode == activeMasternode.pubKeyMasternode)) { + if(!pmn->IsBroadcastedWithin(MASTERNODE_MIN_MNB_SECONDS) || (fMasternodeMode && keyIDMasternode == activeMasternodeInfo.keyIDMasternode)) { // take the newest entry LogPrintf("CMasternodeBroadcast::Update -- Got UPDATED Masternode entry: addr=%s\n", addr.ToString()); if(pmn->UpdateFromNewBroadcast(*this, connman)) { @@ -540,14 +541,14 @@ bool CMasternodeBroadcast::CheckOutpoint(int& nDos) { // we are a masternode with the same outpoint (i.e. already activated) and this mnb is ours (matches our Masternode privkey) // so nothing to do here for us - if(fMasternodeMode && outpoint == activeMasternode.outpoint && pubKeyMasternode == activeMasternode.pubKeyMasternode) { + if(fMasternodeMode && outpoint == activeMasternodeInfo.outpoint && keyIDMasternode == activeMasternodeInfo.keyIDMasternode) { return false; } AssertLockHeld(cs_main); int nHeight; - CollateralStatus err = CheckCollateral(outpoint, pubKeyCollateralAddress, nHeight); + CollateralStatus err = CheckCollateral(outpoint, keyIDCollateralAddress, nHeight); if (err == COLLATERAL_UTXO_NOT_FOUND) { LogPrint("masternode", "CMasternodeBroadcast::CheckOutpoint -- Failed to find Masternode UTXO, masternode=%s\n", outpoint.ToStringShort()); return false; @@ -560,7 +561,7 @@ bool CMasternodeBroadcast::CheckOutpoint(int& nDos) } if(err == COLLATERAL_INVALID_PUBKEY) { - LogPrint("masternode", "CMasternodeBroadcast::CheckOutpoint -- Masternode UTXO should match pubKeyCollateralAddress, masternode=%s\n", outpoint.ToStringShort()); + LogPrint("masternode", "CMasternodeBroadcast::CheckOutpoint -- Masternode UTXO should match keyIDCollateralAddress, masternode=%s\n", outpoint.ToStringShort()); nDos = 33; return false; } @@ -634,21 +635,21 @@ bool CMasternodeBroadcast::Sign(const CKey& keyCollateralAddress) return false; } - if (!CHashSigner::VerifyHash(hash, pubKeyCollateralAddress, vchSig, strError)) { + if (!CHashSigner::VerifyHash(hash, keyIDCollateralAddress, vchSig, strError)) { LogPrintf("CMasternodeBroadcast::Sign -- VerifyMessage() failed, error: %s\n", strError); return false; } } else { - std::string strMessage = addr.ToString(false) + boost::lexical_cast(sigTime) + - pubKeyCollateralAddress.GetID().ToString() + pubKeyMasternode.GetID().ToString() + - boost::lexical_cast(nProtocolVersion); + std::string strMessage = addr.ToString(false) + std::to_string(sigTime) + + keyIDCollateralAddress.ToString() + keyIDMasternode.ToString() + + std::to_string(nProtocolVersion); if (!CMessageSigner::SignMessage(strMessage, vchSig, keyCollateralAddress)) { LogPrintf("CMasternodeBroadcast::Sign -- SignMessage() failed\n"); return false; } - if (!CMessageSigner::VerifyMessage(pubKeyCollateralAddress, vchSig, strMessage, strError)) { + if(!CMessageSigner::VerifyMessage(keyIDCollateralAddress, vchSig, strMessage, strError)) { LogPrintf("CMasternodeBroadcast::Sign -- VerifyMessage() failed, error: %s\n", strError); return false; } @@ -665,13 +666,13 @@ bool CMasternodeBroadcast::CheckSignature(int& nDos) const if (sporkManager.IsSporkActive(SPORK_6_NEW_SIGS)) { uint256 hash = GetSignatureHash(); - if (!CHashSigner::VerifyHash(hash, pubKeyCollateralAddress, vchSig, strError)) { + if (!CHashSigner::VerifyHash(hash, keyIDCollateralAddress, vchSig, strError)) { // maybe it's in old format - std::string strMessage = addr.ToString(false) + boost::lexical_cast(sigTime) + - pubKeyCollateralAddress.GetID().ToString() + pubKeyMasternode.GetID().ToString() + - boost::lexical_cast(nProtocolVersion); + std::string strMessage = addr.ToString(false) + std::to_string(sigTime) + + keyIDCollateralAddress.ToString() + keyIDMasternode.ToString() + + std::to_string(nProtocolVersion); - if (!CMessageSigner::VerifyMessage(pubKeyCollateralAddress, vchSig, strMessage, strError)){ + if (!CMessageSigner::VerifyMessage(keyIDCollateralAddress, vchSig, strMessage, strError)){ // nope, not in old format either LogPrintf("CMasternodeBroadcast::CheckSignature -- Got bad Masternode announce signature, error: %s\n", strError); nDos = 100; @@ -679,11 +680,11 @@ bool CMasternodeBroadcast::CheckSignature(int& nDos) const } } } else { - std::string strMessage = addr.ToString(false) + boost::lexical_cast(sigTime) + - pubKeyCollateralAddress.GetID().ToString() + pubKeyMasternode.GetID().ToString() + - boost::lexical_cast(nProtocolVersion); + std::string strMessage = addr.ToString(false) + std::to_string(sigTime) + + keyIDCollateralAddress.ToString() + keyIDMasternode.ToString() + + std::to_string(nProtocolVersion); - if (!CMessageSigner::VerifyMessage(pubKeyCollateralAddress, vchSig, strMessage, strError)){ + if(!CMessageSigner::VerifyMessage(keyIDCollateralAddress, vchSig, strMessage, strError)){ LogPrintf("CMasternodeBroadcast::CheckSignature -- Got bad Masternode announce signature, error: %s\n", strError); nDos = 100; return false; @@ -741,7 +742,7 @@ CMasternodePing::CMasternodePing(const COutPoint& outpoint) nDaemonVersion = CLIENT_VERSION; } -bool CMasternodePing::Sign(const CKey& keyMasternode, const CPubKey& pubKeyMasternode) +bool CMasternodePing::Sign(const CKey& keyMasternode, const CKeyID& keyIDMasternode) { std::string strError; @@ -755,7 +756,7 @@ bool CMasternodePing::Sign(const CKey& keyMasternode, const CPubKey& pubKeyMaste return false; } - if (!CHashSigner::VerifyHash(hash, pubKeyMasternode, vchSig, strError)) { + if (!CHashSigner::VerifyHash(hash, keyIDMasternode, vchSig, strError)) { LogPrintf("CMasternodePing::Sign -- VerifyHash() failed, error: %s\n", strError); return false; } @@ -768,7 +769,7 @@ bool CMasternodePing::Sign(const CKey& keyMasternode, const CPubKey& pubKeyMaste return false; } - if (!CMessageSigner::VerifyMessage(pubKeyMasternode, vchSig, strMessage, strError)) { + if(!CMessageSigner::VerifyMessage(keyIDMasternode, vchSig, strMessage, strError)) { LogPrintf("CMasternodePing::Sign -- VerifyMessage() failed, error: %s\n", strError); return false; } @@ -777,7 +778,7 @@ bool CMasternodePing::Sign(const CKey& keyMasternode, const CPubKey& pubKeyMaste return true; } -bool CMasternodePing::CheckSignature(const CPubKey& pubKeyMasternode, int &nDos) const +bool CMasternodePing::CheckSignature(CKeyID& keyIDMasternode, int &nDos) const { std::string strError = ""; nDos = 0; @@ -785,11 +786,11 @@ bool CMasternodePing::CheckSignature(const CPubKey& pubKeyMasternode, int &nDos) if (sporkManager.IsSporkActive(SPORK_6_NEW_SIGS)) { uint256 hash = GetSignatureHash(); - if (!CHashSigner::VerifyHash(hash, pubKeyMasternode, vchSig, strError)) { + if (!CHashSigner::VerifyHash(hash, keyIDMasternode, vchSig, strError)) { std::string strMessage = CTxIn(masternodeOutpoint).ToString() + blockHash.ToString() + boost::lexical_cast(sigTime); - if (!CMessageSigner::VerifyMessage(pubKeyMasternode, vchSig, strMessage, strError)) { + if(!CMessageSigner::VerifyMessage(keyIDMasternode, vchSig, strMessage, strError)) { LogPrintf("CMasternodePing::CheckSignature -- Got bad Masternode ping signature, masternode=%s, error: %s\n", masternodeOutpoint.ToStringShort(), strError); nDos = 33; return false; @@ -799,7 +800,7 @@ bool CMasternodePing::CheckSignature(const CPubKey& pubKeyMasternode, int &nDos) std::string strMessage = CTxIn(masternodeOutpoint).ToString() + blockHash.ToString() + boost::lexical_cast(sigTime); - if (!CMessageSigner::VerifyMessage(pubKeyMasternode, vchSig, strMessage, strError)) { + if (!CMessageSigner::VerifyMessage(keyIDMasternode, vchSig, strMessage, strError)) { LogPrintf("CMasternodePing::CheckSignature -- Got bad Masternode ping signature, masternode=%s, error: %s\n", masternodeOutpoint.ToStringShort(), strError); nDos = 33; return false; @@ -883,7 +884,7 @@ bool CMasternodePing::CheckAndUpdate(CMasternode* pmn, bool fFromNewBroadcast, i return false; } - if (!CheckSignature(pmn->pubKeyMasternode, nDos)) return false; + if (!CheckSignature(pmn->keyIDMasternode, nDos)) return false; // so, ping seems to be ok diff --git a/src/masternode.h b/src/masternode.h index f2cee704f2fb..7f799f24301b 100644 --- a/src/masternode.h +++ b/src/masternode.h @@ -97,8 +97,8 @@ class CMasternodePing bool IsExpired() const { return GetAdjustedTime() - sigTime > MASTERNODE_NEW_START_REQUIRED_SECONDS; } - bool Sign(const CKey& keyMasternode, const CPubKey& pubKeyMasternode); - bool CheckSignature(const CPubKey& pubKeyMasternode, int &nDos) const; + bool Sign(const CKey& keyMasternode, const CKeyID& keyIDMasternode); + bool CheckSignature(CKeyID& keyIDMasternode, int &nDos) const; bool SimpleCheck(int& nDos); bool CheckAndUpdate(CMasternode* pmn, bool fFromNewBroadcast, int& nDos, CConnman& connman); void Relay(CConnman& connman); @@ -132,12 +132,21 @@ struct masternode_info_t masternode_info_t(int activeState, int protoVer, int64_t sTime) : nActiveState{activeState}, nProtocolVersion{protoVer}, sigTime{sTime} {} + // only called when the network is in legacy MN list mode masternode_info_t(int activeState, int protoVer, int64_t sTime, COutPoint const& outpnt, CService const& addr, CPubKey const& pkCollAddr, CPubKey const& pkMN) : nActiveState{activeState}, nProtocolVersion{protoVer}, sigTime{sTime}, outpoint{outpnt}, addr{addr}, - pubKeyCollateralAddress{pkCollAddr}, pubKeyMasternode{pkMN} {} + pubKeyCollateralAddress{pkCollAddr}, pubKeyMasternode{pkMN}, keyIDCollateralAddress{pkCollAddr.GetID()}, keyIDMasternode{pkMN.GetID()} {} + + // only called when the network is in deterministic MN list mode + masternode_info_t(int activeState, int protoVer, int64_t sTime, + COutPoint const& outpnt, CService const& addr, + CKeyID const& pkCollAddr, CKeyID const& pkMN) : + nActiveState{activeState}, nProtocolVersion{protoVer}, sigTime{sTime}, + outpoint{outpnt}, addr{addr}, + pubKeyCollateralAddress{}, pubKeyMasternode{}, keyIDCollateralAddress{pkCollAddr}, keyIDMasternode{pkMN} {} int nActiveState = 0; int nProtocolVersion = 0; @@ -145,8 +154,10 @@ struct masternode_info_t COutPoint outpoint{}; CService addr{}; - CPubKey pubKeyCollateralAddress{}; - CPubKey pubKeyMasternode{}; + CPubKey pubKeyCollateralAddress{}; // this will be invalid/unset when the network switches to deterministic MNs (luckely it's only important for the broadcast hash) + CPubKey pubKeyMasternode{}; // this will be invalid/unset when the network switches to deterministic MNs (luckely it's only important for the broadcast hash) + CKeyID keyIDCollateralAddress{}; + CKeyID keyIDMasternode{}; int64_t nLastDsq = 0; //the dsq count from the last dsq broadcast of this node int64_t nTimeLastChecked = 0; @@ -226,6 +237,8 @@ class CMasternode : public masternode_info_t READWRITE(addr); READWRITE(pubKeyCollateralAddress); READWRITE(pubKeyMasternode); + READWRITE(keyIDCollateralAddress); + READWRITE(keyIDMasternode); READWRITE(lastPing); READWRITE(vchSig); READWRITE(sigTime); @@ -248,8 +261,8 @@ class CMasternode : public masternode_info_t bool UpdateFromNewBroadcast(CMasternodeBroadcast& mnb, CConnman& connman); - static CollateralStatus CheckCollateral(const COutPoint& outpoint, const CPubKey& pubkey); - static CollateralStatus CheckCollateral(const COutPoint& outpoint, const CPubKey& pubkey, int& nHeightRet); + static CollateralStatus CheckCollateral(const COutPoint& outpoint, const CKeyID& keyID); + static CollateralStatus CheckCollateral(const COutPoint& outpoint, const CKeyID& keyID, int& nHeightRet); void Check(bool fForce = false); bool IsBroadcastedWithin(int nSeconds) { return GetAdjustedTime() - sigTime < nSeconds; } @@ -391,6 +404,11 @@ class CMasternodeBroadcast : public CMasternode if (!(s.GetType() & SER_GETHASH)) { READWRITE(lastPing); } + + if (ser_action.ForRead()) { + keyIDCollateralAddress = pubKeyCollateralAddress.GetID(); + keyIDMasternode = pubKeyMasternode.GetID(); + } } uint256 GetHash() const; diff --git a/src/masternodeman.cpp b/src/masternodeman.cpp index c1917db8080a..18ff95e43db1 100644 --- a/src/masternodeman.cpp +++ b/src/masternodeman.cpp @@ -26,7 +26,7 @@ /** Masternode manager */ CMasternodeMan mnodeman; -const std::string CMasternodeMan::SERIALIZATION_VERSION_STRING = "CMasternodeMan-Version-8"; +const std::string CMasternodeMan::SERIALIZATION_VERSION_STRING = "CMasternodeMan-Version-9"; const int CMasternodeMan::LAST_PAID_SCAN_BLOCKS = 50; struct CompareLastPaidBlock @@ -472,11 +472,10 @@ bool CMasternodeMan::GetMasternodeInfo(const COutPoint& outpoint, masternode_inf return true; } -bool CMasternodeMan::GetMasternodeInfo(const CPubKey& pubKeyMasternode, masternode_info_t& mnInfoRet) -{ +bool CMasternodeMan::GetMasternodeInfo(const CKeyID& keyIDMasternode, masternode_info_t& mnInfoRet) { LOCK(cs); for (const auto& mnpair : mapMasternodes) { - if (mnpair.second.pubKeyMasternode == pubKeyMasternode) { + if (mnpair.second.keyIDMasternode == keyIDMasternode) { mnInfoRet = mnpair.second.GetInfo(); return true; } @@ -484,17 +483,18 @@ bool CMasternodeMan::GetMasternodeInfo(const CPubKey& pubKeyMasternode, masterno return false; } +bool CMasternodeMan::GetMasternodeInfo(const CPubKey& pubKeyMasternode, masternode_info_t& mnInfoRet) +{ + return GetMasternodeInfo(pubKeyMasternode.GetID(), mnInfoRet); +} + bool CMasternodeMan::GetMasternodeInfo(const CScript& payee, masternode_info_t& mnInfoRet) { - LOCK(cs); - for (const auto& mnpair : mapMasternodes) { - CScript scriptCollateralAddress = GetScriptForDestination(mnpair.second.pubKeyCollateralAddress.GetID()); - if (scriptCollateralAddress == payee) { - mnInfoRet = mnpair.second.GetInfo(); - return true; - } - } - return false; + CTxDestination dest; + if (!ExtractDestination(payee, dest) || !boost::get(&dest)) + return false; + CKeyID keyId = *boost::get(&dest); + return GetMasternodeInfo(keyId, mnInfoRet); } bool CMasternodeMan::Has(const COutPoint& outpoint) @@ -995,7 +995,7 @@ void CMasternodeMan::PushDsegInvs(CNode* pnode, const CMasternode& mn) void CMasternodeMan::DoFullVerificationStep(CConnman& connman) { - if(activeMasternode.outpoint.IsNull()) return; + if(activeMasternodeInfo.outpoint.IsNull()) return; if(!masternodeSync.IsSynced()) return; rank_pair_vec_t vecMasternodeRanks; @@ -1015,7 +1015,7 @@ void CMasternodeMan::DoFullVerificationStep(CConnman& connman) (int)MAX_POSE_RANK); return; } - if(rankPair.second.outpoint == activeMasternode.outpoint) { + if(rankPair.second.outpoint == activeMasternodeInfo.outpoint) { nMyRank = rankPair.first; LogPrint("masternode", "CMasternodeMan::DoFullVerificationStep -- Found self at rank %d/%d, verifying up to %d masternodes\n", nMyRank, nRanksTotal, (int)MAX_POSE_CONNECTIONS); @@ -1200,24 +1200,24 @@ void CMasternodeMan::SendVerifyReply(CNode* pnode, CMasternodeVerification& mnv, if (sporkManager.IsSporkActive(SPORK_6_NEW_SIGS)) { uint256 hash = mnv.GetSignatureHash1(blockHash); - if(!CHashSigner::SignHash(hash, activeMasternode.keyMasternode, mnv.vchSig1)) { + if(!CHashSigner::SignHash(hash, activeMasternodeInfo.keyMasternode, mnv.vchSig1)) { LogPrintf("CMasternodeMan::SendVerifyReply -- SignHash() failed\n"); return; } - if (!CHashSigner::VerifyHash(hash, activeMasternode.pubKeyMasternode, mnv.vchSig1, strError)) { + if (!CHashSigner::VerifyHash(hash, activeMasternodeInfo.keyIDMasternode, mnv.vchSig1, strError)) { LogPrintf("CMasternodeMan::SendVerifyReply -- VerifyHash() failed, error: %s\n", strError); return; } } else { - std::string strMessage = strprintf("%s%d%s", activeMasternode.service.ToString(false), mnv.nonce, blockHash.ToString()); + std::string strMessage = strprintf("%s%d%s", activeMasternodeInfo.service.ToString(false), mnv.nonce, blockHash.ToString()); - if(!CMessageSigner::SignMessage(strMessage, mnv.vchSig1, activeMasternode.keyMasternode)) { + if(!CMessageSigner::SignMessage(strMessage, mnv.vchSig1, activeMasternodeInfo.keyMasternode)) { LogPrintf("MasternodeMan::SendVerifyReply -- SignMessage() failed\n"); return; } - if(!CMessageSigner::VerifyMessage(activeMasternode.pubKeyMasternode, mnv.vchSig1, strMessage, strError)) { + if(!CMessageSigner::VerifyMessage(activeMasternodeInfo.keyIDMasternode, mnv.vchSig1, strMessage, strError)) { LogPrintf("MasternodeMan::SendVerifyReply -- VerifyMessage() failed, error: %s\n", strError); return; } @@ -1284,10 +1284,10 @@ void CMasternodeMan::ProcessVerifyReply(CNode* pnode, CMasternodeVerification& m if(CAddress(mnpair.second.addr, NODE_NETWORK) == pnode->addr) { bool fFound = false; if (sporkManager.IsSporkActive(SPORK_6_NEW_SIGS)) { - fFound = CHashSigner::VerifyHash(hash1, mnpair.second.pubKeyMasternode, mnv.vchSig1, strError); + fFound = CHashSigner::VerifyHash(hash1, mnpair.second.keyIDMasternode, mnv.vchSig1, strError); // we don't care about mnv with signature in old format } else { - fFound = CMessageSigner::VerifyMessage(mnpair.second.pubKeyMasternode, mnv.vchSig1, strMessage1, strError); + fFound = CMessageSigner::VerifyMessage(mnpair.second.keyIDMasternode, mnv.vchSig1, strMessage1, strError); } if (fFound) { // found it! @@ -1298,23 +1298,23 @@ void CMasternodeMan::ProcessVerifyReply(CNode* pnode, CMasternodeVerification& m netfulfilledman.AddFulfilledRequest(pnode->addr, strprintf("%s", NetMsgType::MNVERIFY)+"-done"); // we can only broadcast it if we are an activated masternode - if(activeMasternode.outpoint.IsNull()) continue; + if(activeMasternodeInfo.outpoint.IsNull()) continue; // update ... mnv.addr = mnpair.second.addr; mnv.masternodeOutpoint1 = mnpair.second.outpoint; - mnv.masternodeOutpoint2 = activeMasternode.outpoint; + mnv.masternodeOutpoint2 = activeMasternodeInfo.outpoint; // ... and sign it std::string strError; if (sporkManager.IsSporkActive(SPORK_6_NEW_SIGS)) { uint256 hash2 = mnv.GetSignatureHash2(blockHash); - if(!CHashSigner::SignHash(hash2, activeMasternode.keyMasternode, mnv.vchSig2)) { + if(!CHashSigner::SignHash(hash2, activeMasternodeInfo.keyMasternode, mnv.vchSig2)) { LogPrintf("MasternodeMan::ProcessVerifyReply -- SignHash() failed\n"); return; } - if(!CHashSigner::VerifyHash(hash2, activeMasternode.pubKeyMasternode, mnv.vchSig2, strError)) { + if(!CHashSigner::VerifyHash(hash2, activeMasternodeInfo.keyIDMasternode, mnv.vchSig2, strError)) { LogPrintf("MasternodeMan::ProcessVerifyReply -- VerifyHash() failed, error: %s\n", strError); return; } @@ -1322,12 +1322,12 @@ void CMasternodeMan::ProcessVerifyReply(CNode* pnode, CMasternodeVerification& m std::string strMessage2 = strprintf("%s%d%s%s%s", mnv.addr.ToString(false), mnv.nonce, blockHash.ToString(), mnv.masternodeOutpoint1.ToStringShort(), mnv.masternodeOutpoint2.ToStringShort()); - if(!CMessageSigner::SignMessage(strMessage2, mnv.vchSig2, activeMasternode.keyMasternode)) { + if(!CMessageSigner::SignMessage(strMessage2, mnv.vchSig2, activeMasternodeInfo.keyMasternode)) { LogPrintf("MasternodeMan::ProcessVerifyReply -- SignMessage() failed\n"); return; } - if(!CMessageSigner::VerifyMessage(activeMasternode.pubKeyMasternode, mnv.vchSig2, strMessage2, strError)) { + if(!CMessageSigner::VerifyMessage(activeMasternodeInfo.keyIDMasternode, mnv.vchSig2, strMessage2, strError)) { LogPrintf("MasternodeMan::ProcessVerifyReply -- VerifyMessage() failed, error: %s\n", strError); return; } @@ -1437,12 +1437,12 @@ void CMasternodeMan::ProcessVerifyBroadcast(CNode* pnode, const CMasternodeVerif uint256 hash1 = mnv.GetSignatureHash1(blockHash); uint256 hash2 = mnv.GetSignatureHash2(blockHash); - if(!CHashSigner::VerifyHash(hash1, pmn1->pubKeyMasternode, mnv.vchSig1, strError)) { + if(!CHashSigner::VerifyHash(hash1, pmn1->keyIDMasternode, mnv.vchSig1, strError)) { LogPrintf("MasternodeMan::ProcessVerifyBroadcast -- VerifyHash() failed, error: %s\n", strError); return; } - if(!CHashSigner::VerifyHash(hash2, pmn2->pubKeyMasternode, mnv.vchSig2, strError)) { + if(!CHashSigner::VerifyHash(hash2, pmn2->keyIDMasternode, mnv.vchSig2, strError)) { LogPrintf("MasternodeMan::ProcessVerifyBroadcast -- VerifyHash() failed, error: %s\n", strError); return; } @@ -1451,12 +1451,12 @@ void CMasternodeMan::ProcessVerifyBroadcast(CNode* pnode, const CMasternodeVerif std::string strMessage2 = strprintf("%s%d%s%s%s", mnv.addr.ToString(false), mnv.nonce, blockHash.ToString(), mnv.masternodeOutpoint1.ToStringShort(), mnv.masternodeOutpoint2.ToStringShort()); - if(!CMessageSigner::VerifyMessage(pmn1->pubKeyMasternode, mnv.vchSig1, strMessage1, strError)) { + if(!CMessageSigner::VerifyMessage(pmn1->keyIDMasternode, mnv.vchSig1, strMessage1, strError)) { LogPrintf("CMasternodeMan::ProcessVerifyBroadcast -- VerifyMessage() for masternode1 failed, error: %s\n", strError); return; } - if(!CMessageSigner::VerifyMessage(pmn2->pubKeyMasternode, mnv.vchSig2, strMessage2, strError)) { + if(!CMessageSigner::VerifyMessage(pmn2->keyIDMasternode, mnv.vchSig2, strMessage2, strError)) { LogPrintf("CMasternodeMan::ProcessVerifyBroadcast -- VerifyMessage() for masternode2 failed, error: %s\n", strError); return; } @@ -1568,13 +1568,13 @@ bool CMasternodeMan::CheckMnbAndUpdateMasternodeList(CNode* pfrom, CMasternodeBr Add(mnb); masternodeSync.BumpAssetLastTime("CMasternodeMan::CheckMnbAndUpdateMasternodeList - new"); // if it matches our Masternode privkey... - if(fMasternodeMode && mnb.pubKeyMasternode == activeMasternode.pubKeyMasternode) { + if(fMasternodeMode && mnb.keyIDMasternode == activeMasternodeInfo.keyIDMasternode) { mnb.nPoSeBanScore = -MASTERNODE_POSE_BAN_MAX_SCORE; if(mnb.nProtocolVersion == PROTOCOL_VERSION) { // ... and PROTOCOL_VERSION, then we've been remotely activated ... LogPrintf("CMasternodeMan::CheckMnbAndUpdateMasternodeList -- Got NEW Masternode entry: masternode=%s sigTime=%lld addr=%s\n", mnb.outpoint.ToStringShort(), mnb.sigTime, mnb.addr.ToString()); - activeMasternode.ManageState(connman); + legacyActiveMasternodeManager.ManageState(connman); } else { // ... otherwise we need to reactivate our node, do not add it to the list and do not relay // but also do not ban the node we get this message from @@ -1644,11 +1644,11 @@ void CMasternodeMan::RemoveGovernanceObject(uint256 nGovernanceObjectHash) } } -void CMasternodeMan::CheckMasternode(const CPubKey& pubKeyMasternode, bool fForce) +void CMasternodeMan::CheckMasternode(const CKeyID& keyIDMasternode, bool fForce) { LOCK2(cs_main, cs); for (auto& mnpair : mapMasternodes) { - if (mnpair.second.pubKeyMasternode == pubKeyMasternode) { + if (mnpair.second.keyIDMasternode == keyIDMasternode) { mnpair.second.Check(fForce); return; } diff --git a/src/masternodeman.h b/src/masternodeman.h index 3a31cced9997..2b56910db95b 100644 --- a/src/masternodeman.h +++ b/src/masternodeman.h @@ -170,6 +170,7 @@ class CMasternodeMan bool Has(const COutPoint& outpoint); bool GetMasternodeInfo(const COutPoint& outpoint, masternode_info_t& mnInfoRet); + bool GetMasternodeInfo(const CKeyID& keyIDMasternode, masternode_info_t& mnInfoRet); bool GetMasternodeInfo(const CPubKey& pubKeyMasternode, masternode_info_t& mnInfoRet); bool GetMasternodeInfo(const CScript& payee, masternode_info_t& mnInfoRet); @@ -230,7 +231,7 @@ class CMasternodeMan bool AddGovernanceVote(const COutPoint& outpoint, uint256 nGovernanceObjectHash); void RemoveGovernanceObject(uint256 nGovernanceObjectHash); - void CheckMasternode(const CPubKey& pubKeyMasternode, bool fForce); + void CheckMasternode(const CKeyID& keyIDMasternode, bool fForce); bool IsMasternodePingedWithin(const COutPoint& outpoint, int nSeconds, int64_t nTimeToCheckAt = -1); void SetMasternodeLastPing(const COutPoint& outpoint, const CMasternodePing& mnp); diff --git a/src/net_processing.cpp b/src/net_processing.cpp index 670940f2ea19..3db2b9b76f7d 100644 --- a/src/net_processing.cpp +++ b/src/net_processing.cpp @@ -1973,7 +1973,7 @@ bool static ProcessMessage(CNode* pfrom, const std::string& strCommand, CDataStr // we have no idea about (e.g we were offline)? How to handle them? } - if(!dstx.CheckSignature(mn.pubKeyMasternode)) { + if(!dstx.CheckSignature(mn.keyIDMasternode)) { LogPrint("privatesend", "DSTX -- CheckSignature() failed for %s\n", hashTx.ToString()); return false; } diff --git a/src/privatesend-client.cpp b/src/privatesend-client.cpp index 6c1792f82ef7..1fcb40d9497f 100644 --- a/src/privatesend-client.cpp +++ b/src/privatesend-client.cpp @@ -57,7 +57,7 @@ void CPrivateSendClient::ProcessMessage(CNode* pfrom, const std::string& strComm masternode_info_t infoMn; if(!mnodeman.GetMasternodeInfo(dsq.masternodeOutpoint, infoMn)) return; - if(!dsq.CheckSignature(infoMn.pubKeyMasternode)) { + if(!dsq.CheckSignature(infoMn.keyIDMasternode)) { // we probably have outdated info mnodeman.AskForMN(pfrom, dsq.masternodeOutpoint, connman); return; diff --git a/src/privatesend-server.cpp b/src/privatesend-server.cpp index f914dd916130..c9f49c42e814 100644 --- a/src/privatesend-server.cpp +++ b/src/privatesend-server.cpp @@ -49,7 +49,7 @@ void CPrivateSendServer::ProcessMessage(CNode* pfrom, const std::string& strComm if(dsa.nInputCount < 0 || dsa.nInputCount > PRIVATESEND_ENTRY_MAX_SIZE) return; masternode_info_t mnInfo; - if(!mnodeman.GetMasternodeInfo(activeMasternode.outpoint, mnInfo)) { + if(!mnodeman.GetMasternodeInfo(activeMasternodeInfo.outpoint, mnInfo)) { PushStatus(pfrom, STATUS_REJECTED, ERR_MN_LIST, connman); return; } @@ -106,7 +106,7 @@ void CPrivateSendServer::ProcessMessage(CNode* pfrom, const std::string& strComm masternode_info_t mnInfo; if(!mnodeman.GetMasternodeInfo(dsq.masternodeOutpoint, mnInfo)) return; - if(!dsq.CheckSignature(mnInfo.pubKeyMasternode)) { + if(!dsq.CheckSignature(mnInfo.keyIDMasternode)) { // we probably have outdated info mnodeman.AskForMN(pfrom, dsq.masternodeOutpoint, connman); return; @@ -364,7 +364,7 @@ void CPrivateSendServer::CommitFinalTransaction(CConnman& connman) // create and sign masternode dstx transaction if(!CPrivateSend::GetDSTX(hashTx)) { - CDarksendBroadcastTx dstxNew(finalTransaction, activeMasternode.outpoint, GetAdjustedTime()); + CDarksendBroadcastTx dstxNew(finalTransaction, activeMasternodeInfo.outpoint, GetAdjustedTime()); dstxNew.Sign(); CPrivateSend::AddDSTX(dstxNew); } @@ -525,7 +525,7 @@ void CPrivateSendServer::CheckForCompleteQueue(CConnman& connman) if(nState == POOL_STATE_QUEUE && IsSessionReady()) { SetState(POOL_STATE_ACCEPTING_ENTRIES); - CDarksendQueue dsq(nSessionDenom, nSessionInputCount, activeMasternode.outpoint, GetAdjustedTime(), true); + CDarksendQueue dsq(nSessionDenom, nSessionInputCount, activeMasternodeInfo.outpoint, GetAdjustedTime(), true); LogPrint("privatesend", "CPrivateSendServer::CheckForCompleteQueue -- queue is ready, signing and relaying (%s)\n", dsq.ToString()); dsq.Sign(); dsq.Relay(connman); @@ -740,7 +740,7 @@ bool CPrivateSendServer::CreateNewSession(const CDarksendAccept& dsa, PoolMessag if(!fUnitTest) { //broadcast that I'm accepting entries, only if it's the first entry through - CDarksendQueue dsq(dsa.nDenom, dsa.nInputCount, activeMasternode.outpoint, GetAdjustedTime(), false); + CDarksendQueue dsq(dsa.nDenom, dsa.nInputCount, activeMasternodeInfo.outpoint, GetAdjustedTime(), false); LogPrint("privatesend", "CPrivateSendServer::CreateNewSession -- signing and relaying new queue: %s\n", dsq.ToString()); dsq.Sign(); dsq.Relay(connman); diff --git a/src/privatesend.cpp b/src/privatesend.cpp index 2292008c4ca9..fd1b2168f245 100644 --- a/src/privatesend.cpp +++ b/src/privatesend.cpp @@ -48,12 +48,12 @@ bool CDarksendQueue::Sign() if (sporkManager.IsSporkActive(SPORK_6_NEW_SIGS)) { uint256 hash = GetSignatureHash(); - if (!CHashSigner::SignHash(hash, activeMasternode.keyMasternode, vchSig)) { + if (!CHashSigner::SignHash(hash, activeMasternodeInfo.keyMasternode, vchSig)) { LogPrintf("CDarksendQueue::Sign -- SignHash() failed\n"); return false; } - if (!CHashSigner::VerifyHash(hash, activeMasternode.pubKeyMasternode, vchSig, strError)) { + if (!CHashSigner::VerifyHash(hash, activeMasternodeInfo.keyIDMasternode, vchSig, strError)) { LogPrintf("CDarksendQueue::Sign -- VerifyHash() failed, error: %s\n", strError); return false; } @@ -63,12 +63,12 @@ bool CDarksendQueue::Sign() boost::lexical_cast(nTime) + boost::lexical_cast(fReady); - if(!CMessageSigner::SignMessage(strMessage, vchSig, activeMasternode.keyMasternode)) { + if(!CMessageSigner::SignMessage(strMessage, vchSig, activeMasternodeInfo.keyMasternode)) { LogPrintf("CDarksendQueue::Sign -- SignMessage() failed, %s\n", ToString()); return false; } - if(!CMessageSigner::VerifyMessage(activeMasternode.pubKeyMasternode, vchSig, strMessage, strError)) { + if(!CMessageSigner::VerifyMessage(activeMasternodeInfo.keyIDMasternode, vchSig, strMessage, strError)) { LogPrintf("CDarksendQueue::Sign -- VerifyMessage() failed, error: %s\n", strError); return false; } @@ -77,14 +77,14 @@ bool CDarksendQueue::Sign() return true; } -bool CDarksendQueue::CheckSignature(const CPubKey& pubKeyMasternode) const +bool CDarksendQueue::CheckSignature(const CKeyID& keyIDMasternode) const { std::string strError = ""; if (sporkManager.IsSporkActive(SPORK_6_NEW_SIGS)) { uint256 hash = GetSignatureHash(); - if (!CHashSigner::VerifyHash(hash, pubKeyMasternode, vchSig, strError)) { + if (!CHashSigner::VerifyHash(hash, keyIDMasternode, vchSig, strError)) { // we don't care about queues with old signature format LogPrintf("CDarksendQueue::CheckSignature -- VerifyHash() failed, error: %s\n", strError); return false; @@ -95,7 +95,7 @@ bool CDarksendQueue::CheckSignature(const CPubKey& pubKeyMasternode) const boost::lexical_cast(nTime) + boost::lexical_cast(fReady); - if(!CMessageSigner::VerifyMessage(pubKeyMasternode, vchSig, strMessage, strError)) { + if(!CMessageSigner::VerifyMessage(keyIDMasternode, vchSig, strMessage, strError)) { LogPrintf("CDarksendQueue::CheckSignature -- Got bad Masternode queue signature: %s; error: %s\n", ToString(), strError); return false; } @@ -128,24 +128,24 @@ bool CDarksendBroadcastTx::Sign() if (sporkManager.IsSporkActive(SPORK_6_NEW_SIGS)) { uint256 hash = GetSignatureHash(); - if (!CHashSigner::SignHash(hash, activeMasternode.keyMasternode, vchSig)) { + if (!CHashSigner::SignHash(hash, activeMasternodeInfo.keyMasternode, vchSig)) { LogPrintf("CDarksendBroadcastTx::Sign -- SignHash() failed\n"); return false; } - if (!CHashSigner::VerifyHash(hash, activeMasternode.pubKeyMasternode, vchSig, strError)) { + if (!CHashSigner::VerifyHash(hash, activeMasternodeInfo.keyIDMasternode, vchSig, strError)) { LogPrintf("CDarksendBroadcastTx::Sign -- VerifyHash() failed, error: %s\n", strError); return false; } } else { std::string strMessage = tx->GetHash().ToString() + boost::lexical_cast(sigTime); - if(!CMessageSigner::SignMessage(strMessage, vchSig, activeMasternode.keyMasternode)) { + if(!CMessageSigner::SignMessage(strMessage, vchSig, activeMasternodeInfo.keyMasternode)) { LogPrintf("CDarksendBroadcastTx::Sign -- SignMessage() failed\n"); return false; } - if(!CMessageSigner::VerifyMessage(activeMasternode.pubKeyMasternode, vchSig, strMessage, strError)) { + if(!CMessageSigner::VerifyMessage(activeMasternodeInfo.keyIDMasternode, vchSig, strMessage, strError)) { LogPrintf("CDarksendBroadcastTx::Sign -- VerifyMessage() failed, error: %s\n", strError); return false; } @@ -154,14 +154,14 @@ bool CDarksendBroadcastTx::Sign() return true; } -bool CDarksendBroadcastTx::CheckSignature(const CPubKey& pubKeyMasternode) const +bool CDarksendBroadcastTx::CheckSignature(const CKeyID& keyIDMasternode) const { std::string strError = ""; if (sporkManager.IsSporkActive(SPORK_6_NEW_SIGS)) { uint256 hash = GetSignatureHash(); - if (!CHashSigner::VerifyHash(hash, pubKeyMasternode, vchSig, strError)) { + if (!CHashSigner::VerifyHash(hash, keyIDMasternode, vchSig, strError)) { // we don't care about dstxes with old signature format LogPrintf("CDarksendBroadcastTx::CheckSignature -- VerifyHash() failed, error: %s\n", strError); return false; @@ -169,7 +169,7 @@ bool CDarksendBroadcastTx::CheckSignature(const CPubKey& pubKeyMasternode) const } else { std::string strMessage = tx->GetHash().ToString() + boost::lexical_cast(sigTime); - if(!CMessageSigner::VerifyMessage(pubKeyMasternode, vchSig, strMessage, strError)) { + if(!CMessageSigner::VerifyMessage(keyIDMasternode, vchSig, strMessage, strError)) { LogPrintf("CDarksendBroadcastTx::CheckSignature -- Got bad dstx signature, error: %s\n", strError); return false; } diff --git a/src/privatesend.h b/src/privatesend.h index b3ae1409186d..a664760fdfab 100644 --- a/src/privatesend.h +++ b/src/privatesend.h @@ -250,7 +250,7 @@ class CDarksendQueue */ bool Sign(); /// Check if we have a valid Masternode address - bool CheckSignature(const CPubKey& pubKeyMasternode) const; + bool CheckSignature(const CKeyID& keyIDMasternode) const; bool Relay(CConnman &connman); @@ -342,7 +342,7 @@ class CDarksendBroadcastTx uint256 GetSignatureHash() const; bool Sign(); - bool CheckSignature(const CPubKey& pubKeyMasternode) const; + bool CheckSignature(const CKeyID& keyIDMasternode) const; void SetConfirmedHeight(int nConfirmedHeightIn) { nConfirmedHeight = nConfirmedHeightIn; } bool IsExpired(int nHeight); diff --git a/src/qt/masternodelist.cpp b/src/qt/masternodelist.cpp index 3fec1b433ef5..cb9ca17bdb3f 100644 --- a/src/qt/masternodelist.cpp +++ b/src/qt/masternodelist.cpp @@ -213,8 +213,9 @@ void MasternodeList::updateMyMasternodeInfo(QString strAlias, QString strAddr, c QTableWidgetItem *protocolItem = new QTableWidgetItem(QString::number(fFound ? infoMn.nProtocolVersion : -1)); QTableWidgetItem *statusItem = new QTableWidgetItem(QString::fromStdString(fFound ? CMasternode::StateToString(infoMn.nActiveState) : "MISSING")); QTableWidgetItem *activeSecondsItem = new QTableWidgetItem(QString::fromStdString(DurationToDHMS(fFound ? (infoMn.nTimeLastPing - infoMn.sigTime) : 0))); - QTableWidgetItem *lastSeenItem = new QTableWidgetItem(QString::fromStdString(fFound ? DateTimeStrFormat("%Y-%m-%d %H:%M", infoMn.nTimeLastPing + GetOffsetFromUtc()) : "")); - QTableWidgetItem *pubkeyItem = new QTableWidgetItem(QString::fromStdString(fFound ? CBitcoinAddress(infoMn.pubKeyCollateralAddress.GetID()).ToString() : "")); + QTableWidgetItem *lastSeenItem = new QTableWidgetItem(QString::fromStdString(DateTimeStrFormat("%Y-%m-%d %H:%M", + fFound ? infoMn.nTimeLastPing + GetOffsetFromUtc() : 0))); + QTableWidgetItem *pubkeyItem = new QTableWidgetItem(QString::fromStdString(fFound ? CBitcoinAddress(infoMn.keyIDCollateralAddress).ToString() : "")); ui->tableWidgetMyMasternodes->setItem(nNewRow, 0, aliasItem); ui->tableWidgetMyMasternodes->setItem(nNewRow, 1, addrItem); @@ -301,7 +302,7 @@ void MasternodeList::updateNodeList() QTableWidgetItem *statusItem = new QTableWidgetItem(QString::fromStdString(mn.GetStatus())); QTableWidgetItem *activeSecondsItem = new QTableWidgetItem(QString::fromStdString(DurationToDHMS(mn.lastPing.sigTime - mn.sigTime))); QTableWidgetItem *lastSeenItem = new QTableWidgetItem(QString::fromStdString(DateTimeStrFormat("%Y-%m-%d %H:%M", mn.lastPing.sigTime + offsetFromUtc))); - QTableWidgetItem *pubkeyItem = new QTableWidgetItem(QString::fromStdString(CBitcoinAddress(mn.pubKeyCollateralAddress.GetID()).ToString())); + QTableWidgetItem *pubkeyItem = new QTableWidgetItem(QString::fromStdString(CBitcoinAddress(mn.keyIDCollateralAddress).ToString())); if (strCurrentFilter != "") { diff --git a/src/rpc/governance.cpp b/src/rpc/governance.cpp index 52dcde2c4070..31efd08726ff 100644 --- a/src/rpc/governance.cpp +++ b/src/rpc/governance.cpp @@ -224,10 +224,10 @@ UniValue gobject(const JSONRPCRequest& request) throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "Must wait for client to sync with masternode network. Try again in a minute or so."); } - bool fMnFound = mnodeman.Has(activeMasternode.outpoint); + bool fMnFound = mnodeman.Has(activeMasternodeInfo.outpoint); - DBG( std::cout << "gobject: submit activeMasternode.pubKeyMasternode = " << activeMasternode.pubKeyMasternode.GetHash().ToString() - << ", outpoint = " << activeMasternode.outpoint.ToStringShort() + DBG( std::cout << "gobject: submit activeMasternodeInfo.keyIDMasternode = " << activeMasternodeInfo.keyIDMasternode.ToString() + << ", outpoint = " << activeMasternodeInfo.outpoint.ToStringShort() << ", params.size() = " << request.params.size() << ", fMnFound = " << fMnFound << std::endl; ); @@ -275,8 +275,8 @@ UniValue gobject(const JSONRPCRequest& request) // Attempt to sign triggers if we are a MN if(govobj.GetObjectType() == GOVERNANCE_OBJECT_TRIGGER) { if(fMnFound) { - govobj.SetMasternodeOutpoint(activeMasternode.outpoint); - govobj.Sign(activeMasternode.keyMasternode, activeMasternode.pubKeyMasternode); + govobj.SetMasternodeOutpoint(activeMasternodeInfo.outpoint); + govobj.Sign(activeMasternodeInfo.keyMasternode, activeMasternodeInfo.keyIDMasternode); } else { LogPrintf("gobject(submit) -- Object submission rejected because node is not a masternode\n"); @@ -358,7 +358,7 @@ UniValue gobject(const JSONRPCRequest& request) UniValue returnObj(UniValue::VOBJ); CMasternode mn; - bool fMnFound = mnodeman.Get(activeMasternode.outpoint, mn); + bool fMnFound = mnodeman.Get(activeMasternodeInfo.outpoint, mn); if(!fMnFound) { nFailed++; @@ -371,7 +371,7 @@ UniValue gobject(const JSONRPCRequest& request) } CGovernanceVote vote(mn.outpoint, hash, eVoteSignal, eVoteOutcome); - if(!vote.Sign(activeMasternode.keyMasternode, activeMasternode.pubKeyMasternode)) { + if(!vote.Sign(activeMasternodeInfo.keyMasternode, activeMasternodeInfo.keyIDMasternode)) { nFailed++; statusObj.push_back(Pair("result", "failed")); statusObj.push_back(Pair("errorMessage", "Failure to sign.")); @@ -444,8 +444,6 @@ UniValue gobject(const JSONRPCRequest& request) std::vector vchMasterNodeSignature; std::string strMasterNodeSignMessage; - CPubKey pubKeyCollateralAddress; - CKey keyCollateralAddress; CPubKey pubKeyMasternode; CKey keyMasternode; @@ -481,7 +479,7 @@ UniValue gobject(const JSONRPCRequest& request) } CGovernanceVote vote(mn.outpoint, hash, eVoteSignal, eVoteOutcome); - if(!vote.Sign(keyMasternode, pubKeyMasternode)){ + if(!vote.Sign(keyMasternode, pubKeyMasternode.GetID())){ nFailed++; statusObj.push_back(Pair("result", "failed")); statusObj.push_back(Pair("errorMessage", "Failure to sign.")); diff --git a/src/rpc/masternode.cpp b/src/rpc/masternode.cpp index 12c11cf40f2b..c3b3ed6930f0 100644 --- a/src/rpc/masternode.cpp +++ b/src/rpc/masternode.cpp @@ -253,7 +253,7 @@ UniValue masternode(const JSONRPCRequest& request) obj.push_back(Pair("IP:port", mnInfo.addr.ToString())); obj.push_back(Pair("protocol", mnInfo.nProtocolVersion)); obj.push_back(Pair("outpoint", mnInfo.outpoint.ToStringShort())); - obj.push_back(Pair("payee", CBitcoinAddress(mnInfo.pubKeyCollateralAddress.GetID()).ToString())); + obj.push_back(Pair("payee", CBitcoinAddress(mnInfo.keyIDCollateralAddress).ToString())); obj.push_back(Pair("lastseen", mnInfo.nTimeLastPing)); obj.push_back(Pair("activeseconds", mnInfo.nTimeLastPing - mnInfo.sigTime)); return obj; @@ -430,15 +430,15 @@ UniValue masternode(const JSONRPCRequest& request) UniValue mnObj(UniValue::VOBJ); - mnObj.push_back(Pair("outpoint", activeMasternode.outpoint.ToStringShort())); - mnObj.push_back(Pair("service", activeMasternode.service.ToString())); + mnObj.push_back(Pair("outpoint", activeMasternodeInfo.outpoint.ToStringShort())); + mnObj.push_back(Pair("service", activeMasternodeInfo.service.ToString())); CMasternode mn; - if(mnodeman.Get(activeMasternode.outpoint, mn)) { - mnObj.push_back(Pair("payee", CBitcoinAddress(mn.pubKeyCollateralAddress.GetID()).ToString())); + if(mnodeman.Get(activeMasternodeInfo.outpoint, mn)) { + mnObj.push_back(Pair("payee", CBitcoinAddress(mn.keyIDCollateralAddress).ToString())); } - mnObj.push_back(Pair("status", activeMasternode.GetStatus())); + mnObj.push_back(Pair("status", legacyActiveMasternodeManager.GetStatus())); return mnObj; } @@ -518,7 +518,7 @@ UniValue masternodelist(const JSONRPCRequest& request) " payee - Print Absolute address associated with a masternode (can be additionally filtered,\n" " partial match)\n" " protocol - Print protocol of a masternode (can be additionally filtered, exact match)\n" - " pubkey - Print the masternode (not collateral) public key\n" + " keyid - Print the masternode (not collateral) key id\n" " rank - Print rank of a masternode based on current block\n" " sentinel - Print sentinel version of a masternode (can be additionally filtered, exact match)\n" " status - Print masternode status: PRE_ENABLED / ENABLED / EXPIRED / NO_SENTINEL_PING / NEW_START_REQUIRED /\n" @@ -572,7 +572,7 @@ UniValue masternodelist(const JSONRPCRequest& request) streamFull << std::setw(18) << mn.GetStatus() << " " << mn.nProtocolVersion << " " << - CBitcoinAddress(mn.pubKeyCollateralAddress.GetID()).ToString() << " " << + CBitcoinAddress(mn.keyIDCollateralAddress).ToString() << " " << (int64_t)mn.lastPing.sigTime << " " << std::setw(8) << (int64_t)(mn.lastPing.sigTime - mn.sigTime) << " " << std::setw(10) << mn.GetLastPaidTime() << " " << std::setw(6) << @@ -587,7 +587,7 @@ UniValue masternodelist(const JSONRPCRequest& request) streamInfo << std::setw(18) << mn.GetStatus() << " " << mn.nProtocolVersion << " " << - CBitcoinAddress(mn.pubKeyCollateralAddress.GetID()).ToString() << " " << + CBitcoinAddress(mn.keyIDCollateralAddress).ToString() << " " << (int64_t)mn.lastPing.sigTime << " " << std::setw(8) << (int64_t)(mn.lastPing.sigTime - mn.sigTime) << " " << mn.lastPing.GetSentinelString() << " " << @@ -636,7 +636,7 @@ UniValue masternodelist(const JSONRPCRequest& request) if (strFilter !="" && strOutpoint.find(strFilter) == std::string::npos) continue; obj.push_back(Pair(strOutpoint, (int64_t)mn.lastPing.sigTime)); } else if (strMode == "payee") { - CBitcoinAddress address(mn.pubKeyCollateralAddress.GetID()); + CBitcoinAddress address(mn.keyIDCollateralAddress); std::string strPayee = address.ToString(); if (strFilter !="" && strPayee.find(strFilter) == std::string::npos && strOutpoint.find(strFilter) == std::string::npos) continue; @@ -645,9 +645,9 @@ UniValue masternodelist(const JSONRPCRequest& request) if (strFilter !="" && strFilter != strprintf("%d", mn.nProtocolVersion) && strOutpoint.find(strFilter) == std::string::npos) continue; obj.push_back(Pair(strOutpoint, mn.nProtocolVersion)); - } else if (strMode == "pubkey") { + } else if (strMode == "keyid") { if (strFilter !="" && strOutpoint.find(strFilter) == std::string::npos) continue; - obj.push_back(Pair(strOutpoint, HexStr(mn.pubKeyMasternode))); + obj.push_back(Pair(strOutpoint, HexStr(mn.keyIDMasternode))); } else if (strMode == "status") { std::string strStatus = mn.GetStatus(); if (strFilter !="" && strStatus.find(strFilter) == std::string::npos && @@ -832,8 +832,8 @@ UniValue masternodebroadcast(const JSONRPCRequest& request) nSuccessful++; resultObj.push_back(Pair("outpoint", mnb.outpoint.ToStringShort())); resultObj.push_back(Pair("addr", mnb.addr.ToString())); - resultObj.push_back(Pair("pubKeyCollateralAddress", CBitcoinAddress(mnb.pubKeyCollateralAddress.GetID()).ToString())); - resultObj.push_back(Pair("pubKeyMasternode", CBitcoinAddress(mnb.pubKeyMasternode.GetID()).ToString())); + resultObj.push_back(Pair("keyIDCollateralAddress", CBitcoinAddress(mnb.keyIDCollateralAddress).ToString())); + resultObj.push_back(Pair("keyIDMasternode", CBitcoinAddress(mnb.keyIDMasternode).ToString())); resultObj.push_back(Pair("vchSig", EncodeBase64(&mnb.vchSig[0], mnb.vchSig.size()))); resultObj.push_back(Pair("sigTime", mnb.sigTime)); resultObj.push_back(Pair("protocolVersion", mnb.nProtocolVersion)); @@ -924,7 +924,7 @@ UniValue sentinelping(const JSONRPCRequest& request) ); } - activeMasternode.UpdateSentinelPing(StringVersionToInt(request.params[0].get_str())); + legacyActiveMasternodeManager.UpdateSentinelPing(StringVersionToInt(request.params[0].get_str())); return true; } From e03a43d4a0a42bd543642a0415c4825e850d28a9 Mon Sep 17 00:00:00 2001 From: Alexander Block Date: Sun, 12 Aug 2018 17:27:09 +0200 Subject: [PATCH 039/282] Refactor MN payee logic in preparation for AIP3 1. Move out old budget validation into it's own function (IsOldBudgetBlockValueValid) 2. Refactor IsBlockValueValid to bail out early instead of using deep nested if/else blocks. IMHO, I feel that this makes the code much easier to read and less error prone. 3. Refactor/rename CreateSuperblock and CMasternodePayments::FillBlockPayee to be getters without actually modifying the coinbase TX. The coinbase is now only modified from the global FillBlockPayments function. Makes later changes in AIP3 easier (allowing superblock and MN rewards in same block) * Use __func__ for logging in block payee code --- src/governance-classes.cpp | 41 ++--- src/governance-classes.h | 2 +- src/masternode-payments.cpp | 289 ++++++++++++++++++++---------------- src/masternode-payments.h | 4 +- 4 files changed, 184 insertions(+), 152 deletions(-) diff --git a/src/governance-classes.cpp b/src/governance-classes.cpp index 2dfdccfa934b..22dd26173747 100644 --- a/src/governance-classes.cpp +++ b/src/governance-classes.cpp @@ -367,14 +367,14 @@ bool CSuperblockManager::GetBestSuperblock(CSuperblock_sptr& pSuperblockRet, int } /** -* Create Superblock Payments +* Get Superblock Payments * -* - Create the correct payment structure for a given superblock +* - Returns payments for superblock */ -void CSuperblockManager::CreateSuperblock(CMutableTransaction& txNewRet, int nBlockHeight, std::vector& voutSuperblockRet) +bool CSuperblockManager::GetSuperblockPayments(int nBlockHeight, std::vector& voutSuperblockRet) { - DBG( std::cout << "CSuperblockManager::CreateSuperblock Start" << std::endl; ); + DBG( std::cout << "CSuperblockManager::GetSuperblockPayments Start" << std::endl; ); LOCK(governance.cs); @@ -382,18 +382,18 @@ void CSuperblockManager::CreateSuperblock(CMutableTransaction& txNewRet, int nBl CSuperblock_sptr pSuperblock; if(!CSuperblockManager::GetBestSuperblock(pSuperblock, nBlockHeight)) { - LogPrint("gobject", "CSuperblockManager::CreateSuperblock -- Can't find superblock for height %d\n", nBlockHeight); - DBG( std::cout << "CSuperblockManager::CreateSuperblock Failed to get superblock for height, returning" << std::endl; ); - return; + LogPrint("gobject", "CSuperblockManager::GetSuperblockPayments -- Can't find superblock for height %d\n", nBlockHeight); + DBG( std::cout << "CSuperblockManager::GetSuperblockPayments Failed to get superblock for height, returning" << std::endl; ); + return false; } // make sure it's empty, just in case voutSuperblockRet.clear(); - // CONFIGURE SUPERBLOCK OUTPUTS + // GET SUPERBLOCK OUTPUTS - // Superblock payments are appended to the end of the coinbase vout vector - DBG( std::cout << "CSuperblockManager::CreateSuperblock Number payments: " << pSuperblock->CountPayments() << std::endl; ); + // Superblock payments will be appended to the end of the coinbase vout vector + DBG( std::cout << "CSuperblockManager::GetSuperblockPayments Number payments: " << pSuperblock->CountPayments() << std::endl; ); // TODO: How many payments can we add before things blow up? // Consider at least following limits: @@ -401,13 +401,12 @@ void CSuperblockManager::CreateSuperblock(CMutableTransaction& txNewRet, int nBl // - max "budget" available for(int i = 0; i < pSuperblock->CountPayments(); i++) { CGovernancePayment payment; - DBG( std::cout << "CSuperblockManager::CreateSuperblock i = " << i << std::endl; ); + DBG( std::cout << "CSuperblockManager::GetSuperblockPayments i = " << i << std::endl; ); if(pSuperblock->GetPayment(i, payment)) { - DBG( std::cout << "CSuperblockManager::CreateSuperblock Payment found " << std::endl; ); + DBG( std::cout << "CSuperblockManager::GetSuperblockPayments Payment found " << std::endl; ); // SET COINBASE OUTPUT TO SUPERBLOCK SETTING CTxOut txout = CTxOut(payment.nAmount, payment.script); - txNewRet.vout.push_back(txout); voutSuperblockRet.push_back(txout); // PRINT NICE LOG OUTPUT FOR SUPERBLOCK PAYMENT @@ -418,15 +417,17 @@ void CSuperblockManager::CreateSuperblock(CMutableTransaction& txNewRet, int nBl // TODO: PRINT NICE N.N ABSOLUTE OUTPUT - DBG( std::cout << "CSuperblockManager::CreateSuperblock Before LogPrintf call, nAmount = " << payment.nAmount << std::endl; ); + DBG( std::cout << "CSuperblockManager::GetSuperblockPayments Before LogPrintf call, nAmount = " << payment.nAmount << std::endl; ); LogPrintf("NEW Superblock : output %d (addr %s, amount %d)\n", i, address2.ToString(), payment.nAmount); - DBG( std::cout << "CSuperblockManager::CreateSuperblock After LogPrintf call " << std::endl; ); + DBG( std::cout << "CSuperblockManager::GetSuperblockPayments After LogPrintf call " << std::endl; ); } else { - DBG( std::cout << "CSuperblockManager::CreateSuperblock Payment not found " << std::endl; ); + DBG( std::cout << "CSuperblockManager::GetSuperblockPayments Payment not found " << std::endl; ); } } - DBG( std::cout << "CSuperblockManager::CreateSuperblock End" << std::endl; ); + DBG( std::cout << "CSuperblockManager::GetSuperblockPayments End" << std::endl; ); + + return true; } bool CSuperblockManager::IsValid(const CTransaction& txNew, int nBlockHeight, CAmount blockReward) @@ -680,7 +681,7 @@ bool CSuperblock::IsValid(const CTransaction& txNew, int nBlockHeight, CAmount b int nOutputs = txNew.vout.size(); int nPayments = CountPayments(); - int nMinerPayments = nOutputs - nPayments; + int nMinerAndMasternodePayments = nOutputs - nPayments; LogPrint("gobject", "CSuperblock::IsValid nOutputs = %d, nPayments = %d, GetDataAsHexString = %s\n", nOutputs, nPayments, GetGovernanceObject()->GetDataAsHexString()); @@ -688,7 +689,7 @@ bool CSuperblock::IsValid(const CTransaction& txNew, int nBlockHeight, CAmount b // We require an exact match (including order) between the expected // superblock payments and the payments actually in the block. - if(nMinerPayments < 0) { + if(nMinerAndMasternodePayments < 0) { // This means the block cannot have all the superblock payments // so it is not valid. // TODO: could that be that we just hit coinbase size limit? @@ -704,7 +705,7 @@ bool CSuperblock::IsValid(const CTransaction& txNew, int nBlockHeight, CAmount b return false; } - // miner should not get more than he would usually get + // miner and masternodes should not get more than they would usually get CAmount nBlockValue = txNew.GetValueOut(); if(nBlockValue > blockReward + nPaymentsTotalAmount) { LogPrintf("CSuperblock::IsValid -- ERROR: Block invalid, block value limit exceeded: block %lld, limit %lld\n", nBlockValue, blockReward + nPaymentsTotalAmount); diff --git a/src/governance-classes.h b/src/governance-classes.h index d15ffc9abe20..308d8a8fa0c0 100644 --- a/src/governance-classes.h +++ b/src/governance-classes.h @@ -70,7 +70,7 @@ class CSuperblockManager static bool IsSuperblockTriggered(int nBlockHeight); - static void CreateSuperblock(CMutableTransaction& txNewRet, int nBlockHeight, std::vector& voutSuperblockRet); + static bool GetSuperblockPayments(int nBlockHeight, std::vector& voutSuperblockRet); static void ExecuteBestSuperblock(int nBlockHeight); static std::string GetRequiredPaymentsString(int nBlockHeight); diff --git a/src/masternode-payments.cpp b/src/masternode-payments.cpp index 8f6c44319a7d..9b123f6e9cd9 100644 --- a/src/masternode-payments.cpp +++ b/src/masternode-payments.cpp @@ -24,6 +24,45 @@ CCriticalSection cs_vecPayees; CCriticalSection cs_mapMasternodeBlocks; CCriticalSection cs_mapMasternodePaymentVotes; +bool IsOldBudgetBlockValueValid(const CBlock& block, int nBlockHeight, CAmount blockReward, std::string& strErrorRet) { + const Consensus::Params& consensusParams = Params().GetConsensus(); + + if (nBlockHeight >= consensusParams.nSuperblockStartBlock) { + // switched to new budget system (superblocks) + return true; + } + + bool isBlockRewardValueMet = (block.vtx[0]->GetValueOut() <= blockReward); + + // we are still using budgets, but we have no data about them anymore, + // all we know is predefined budget cycle and window + + int nOffset = nBlockHeight % consensusParams.nBudgetPaymentsCycleBlocks; + if(nBlockHeight >= consensusParams.nBudgetPaymentsStartBlock && + nOffset < consensusParams.nBudgetPaymentsWindowBlocks) { + // NOTE: old budget system is disabled since 12.1 + if(masternodeSync.IsSynced()) { + // no old budget blocks should be accepted here on mainnet, + // testnet/devnet/regtest should produce regular blocks only + LogPrint("gobject", "%s -- WARNING: Client synced but old budget system is disabled, checking block value against block reward\n", __func__); + if(!isBlockRewardValueMet) { + strErrorRet = strprintf("coinbase pays too much at height %d (actual=%d vs limit=%d), exceeded block reward, old budgets are disabled", + nBlockHeight, block.vtx[0]->GetValueOut(), blockReward); + } + return isBlockRewardValueMet; + } + // when not synced, rely on online nodes (all networks) + LogPrint("gobject", "%s -- WARNING: Skipping old budget block value checks, accepting block\n", __func__); + return true; + } + // LogPrint("gobject", "%s -- Block is not in budget cycle window, checking block value against block reward\n", __func__); + if(!isBlockRewardValueMet) { + strErrorRet = strprintf("coinbase pays too much at height %d (actual=%d vs limit=%d), exceeded block reward, block is not in old budget cycle window", + nBlockHeight, block.vtx[0]->GetValueOut(), blockReward); + } + return isBlockRewardValueMet; +} + /** * IsBlockValueValid * @@ -39,105 +78,82 @@ bool IsBlockValueValid(const CBlock& block, int nBlockHeight, CAmount blockRewar { strErrorRet = ""; + if (!IsOldBudgetBlockValueValid(block, nBlockHeight, blockReward, strErrorRet)) { + return false; + } + bool isBlockRewardValueMet = (block.vtx[0]->GetValueOut() <= blockReward); if(fDebug) LogPrintf("block.vtx[0]->GetValueOut() %lld <= blockReward %lld\n", block.vtx[0]->GetValueOut(), blockReward); - // we are still using budgets, but we have no data about them anymore, - // all we know is predefined budget cycle and window + CAmount nSuperblockMaxValue = blockReward + CSuperblock::GetPaymentsLimit(nBlockHeight); + bool isSuperblockMaxValueMet = (block.vtx[0]->GetValueOut() <= nSuperblockMaxValue); - const Consensus::Params& consensusParams = Params().GetConsensus(); + LogPrint("gobject", "block.vtx[0]->GetValueOut() %lld <= nSuperblockMaxValue %lld\n", block.vtx[0]->GetValueOut(), nSuperblockMaxValue); - if(nBlockHeight < consensusParams.nSuperblockStartBlock) { - int nOffset = nBlockHeight % consensusParams.nBudgetPaymentsCycleBlocks; - if(nBlockHeight >= consensusParams.nBudgetPaymentsStartBlock && - nOffset < consensusParams.nBudgetPaymentsWindowBlocks) { - // NOTE: old budget system is disabled since 12.1 - if(masternodeSync.IsSynced()) { - // no old budget blocks should be accepted here on mainnet, - // testnet/devnet/regtest should produce regular blocks only - LogPrint("gobject", "IsBlockValueValid -- WARNING: Client synced but old budget system is disabled, checking block value against block reward\n"); - if(!isBlockRewardValueMet) { - strErrorRet = strprintf("coinbase pays too much at height %d (actual=%d vs limit=%d), exceeded block reward, old budgets are disabled", - nBlockHeight, block.vtx[0]->GetValueOut(), blockReward); - } - return isBlockRewardValueMet; - } - // when not synced, rely on online nodes (all networks) - LogPrint("gobject", "IsBlockValueValid -- WARNING: Skipping old budget block value checks, accepting block\n"); - return true; - } - // LogPrint("gobject", "IsBlockValueValid -- Block is not in budget cycle window, checking block value against block reward\n"); - if(!isBlockRewardValueMet) { - strErrorRet = strprintf("coinbase pays too much at height %d (actual=%d vs limit=%d), exceeded block reward, block is not in old budget cycle window", + if (!CSuperblock::IsValidBlockHeight(nBlockHeight)) { + // can't possibly be a superblock, so lets just check for block reward limits + if (!isBlockRewardValueMet) { + strErrorRet = strprintf("coinbase pays too much at height %d (actual=%d vs limit=%d), exceeded block reward, only regular blocks are allowed at this height", nBlockHeight, block.vtx[0]->GetValueOut(), blockReward); } return isBlockRewardValueMet; } - // superblocks started + // bail out in case superblock limits were exceeded + if (!isSuperblockMaxValueMet) { + strErrorRet = strprintf("coinbase pays too much at height %d (actual=%d vs limit=%d), exceeded superblock max value", + nBlockHeight, block.vtx[0]->GetValueOut(), nSuperblockMaxValue); + return false; + } - CAmount nSuperblockMaxValue = blockReward + CSuperblock::GetPaymentsLimit(nBlockHeight); - bool isSuperblockMaxValueMet = (block.vtx[0]->GetValueOut() <= nSuperblockMaxValue); + if(!masternodeSync.IsSynced() || fLiteMode) { + if(fDebug) LogPrintf("%s -- WARNING: Not enough data, checked superblock max bounds only\n", __func__); + // not enough data for full checks but at least we know that the superblock limits were honored. + // We rely on the network to have followed the correct chain in this case + return true; + } - LogPrint("gobject", "block.vtx[0]->GetValueOut() %lld <= nSuperblockMaxValue %lld\n", block.vtx[0]->GetValueOut(), nSuperblockMaxValue); + // we are synced and possibly on a superblock now - if(!masternodeSync.IsSynced() || fLiteMode) { - // not enough data but at least it must NOT exceed superblock max value - if(CSuperblock::IsValidBlockHeight(nBlockHeight)) { - if(fDebug) LogPrintf("IsBlockPayeeValid -- WARNING: Not enough data, checking superblock max bounds only\n"); - if(!isSuperblockMaxValueMet) { - strErrorRet = strprintf("coinbase pays too much at height %d (actual=%d vs limit=%d), exceeded superblock max value", - nBlockHeight, block.vtx[0]->GetValueOut(), nSuperblockMaxValue); - } - return isSuperblockMaxValueMet; - } + if (!sporkManager.IsSporkActive(SPORK_9_SUPERBLOCKS_ENABLED)) { + // should NOT allow superblocks at all, when superblocks are disabled + // revert to block reward limits in this case + LogPrint("gobject", "%s -- Superblocks are disabled, no superblocks allowed\n", __func__); if(!isBlockRewardValueMet) { - strErrorRet = strprintf("coinbase pays too much at height %d (actual=%d vs limit=%d), exceeded block reward, only regular blocks are allowed at this height", + strErrorRet = strprintf("coinbase pays too much at height %d (actual=%d vs limit=%d), exceeded block reward, superblocks are disabled", nBlockHeight, block.vtx[0]->GetValueOut(), blockReward); } - // it MUST be a regular block otherwise return isBlockRewardValueMet; } - // we are synced, let's try to check as much data as we can - - if(sporkManager.IsSporkActive(SPORK_9_SUPERBLOCKS_ENABLED)) { - if(CSuperblockManager::IsSuperblockTriggered(nBlockHeight)) { - if(CSuperblockManager::IsValid(*block.vtx[0], nBlockHeight, blockReward)) { - LogPrint("gobject", "IsBlockValueValid -- Valid superblock at height %d: %s", nBlockHeight, block.vtx[0]->ToString()); - // all checks are done in CSuperblock::IsValid, nothing to do here - return true; - } - - // triggered but invalid? that's weird - LogPrintf("IsBlockValueValid -- ERROR: Invalid superblock detected at height %d: %s", nBlockHeight, block.vtx[0]->ToString()); - // should NOT allow invalid superblocks, when superblocks are enabled - strErrorRet = strprintf("invalid superblock detected at height %d", nBlockHeight); - return false; - } - LogPrint("gobject", "IsBlockValueValid -- No triggered superblock detected at height %d\n", nBlockHeight); + if (!CSuperblockManager::IsSuperblockTriggered(nBlockHeight)) { + // we are on a valid superblock height but a superblock was not triggered + // revert to block reward limits in this case if(!isBlockRewardValueMet) { strErrorRet = strprintf("coinbase pays too much at height %d (actual=%d vs limit=%d), exceeded block reward, no triggered superblock detected", nBlockHeight, block.vtx[0]->GetValueOut(), blockReward); } - } else { - // should NOT allow superblocks at all, when superblocks are disabled - LogPrint("gobject", "IsBlockValueValid -- Superblocks are disabled, no superblocks allowed\n"); - if(!isBlockRewardValueMet) { - strErrorRet = strprintf("coinbase pays too much at height %d (actual=%d vs limit=%d), exceeded block reward, superblocks are disabled", - nBlockHeight, block.vtx[0]->GetValueOut(), blockReward); - } + return isBlockRewardValueMet; } - // it MUST be a regular block - return isBlockRewardValueMet; + // this actually also checks for correct payees and not only amount + if (!CSuperblockManager::IsValid(*block.vtx[0], nBlockHeight, blockReward)) { + // triggered but invalid? that's weird + LogPrintf("%s -- ERROR: Invalid superblock detected at height %d: %s", __func__, nBlockHeight, block.vtx[0]->ToString()); + // should NOT allow invalid superblocks, when superblocks are enabled + strErrorRet = strprintf("invalid superblock detected at height %d", nBlockHeight); + return false; + } + + // we got a valid superblock + return true; } bool IsBlockPayeeValid(const CTransaction& txNew, int nBlockHeight, CAmount blockReward) { if(!masternodeSync.IsSynced() || fLiteMode) { //there is no budget data to use to check anything, let's just accept the longest chain - if(fDebug) LogPrintf("IsBlockPayeeValid -- WARNING: Not enough data, skipping block payee checks\n"); + if(fDebug) LogPrintf("%s -- WARNING: Not enough data, skipping block payee checks\n", __func__); return true; } @@ -150,7 +166,7 @@ bool IsBlockPayeeValid(const CTransaction& txNew, int nBlockHeight, CAmount bloc // NOTE: old budget system is disabled since 12.1 and we should never enter this branch // anymore when sync is finished (on mainnet). We have no old budget data but these blocks // have tons of confirmations and can be safely accepted without payee verification - LogPrint("gobject", "IsBlockPayeeValid -- WARNING: Client synced but old budget system is disabled, accepting any payee\n"); + LogPrint("gobject", "%s -- WARNING: Client synced but old budget system is disabled, accepting any payee\n", __func__); return true; } @@ -160,33 +176,33 @@ bool IsBlockPayeeValid(const CTransaction& txNew, int nBlockHeight, CAmount bloc if(sporkManager.IsSporkActive(SPORK_9_SUPERBLOCKS_ENABLED)) { if(CSuperblockManager::IsSuperblockTriggered(nBlockHeight)) { if(CSuperblockManager::IsValid(txNew, nBlockHeight, blockReward)) { - LogPrint("gobject", "IsBlockPayeeValid -- Valid superblock at height %d: %s", nBlockHeight, txNew.ToString()); + LogPrint("gobject", "%s -- Valid superblock at height %d: %s", __func__, nBlockHeight, txNew.ToString()); return true; + } else { + LogPrintf("%s -- ERROR: Invalid superblock detected at height %d: %s", __func__, nBlockHeight, txNew.ToString()); + // should NOT allow such superblocks, when superblocks are enabled + return false; } - - LogPrintf("IsBlockPayeeValid -- ERROR: Invalid superblock detected at height %d: %s", nBlockHeight, txNew.ToString()); - // should NOT allow such superblocks, when superblocks are enabled - return false; + } else { + LogPrint("gobject", "%s -- No triggered superblock detected at height %d\n", __func__, nBlockHeight); } - // continue validation, should pay MN - LogPrint("gobject", "IsBlockPayeeValid -- No triggered superblock detected at height %d\n", nBlockHeight); } else { // should NOT allow superblocks at all, when superblocks are disabled - LogPrint("gobject", "IsBlockPayeeValid -- Superblocks are disabled, no superblocks allowed\n"); + LogPrint("gobject", "%s -- Superblocks are disabled, no superblocks allowed\n", __func__); } - // IF THIS ISN'T A SUPERBLOCK OR SUPERBLOCK IS INVALID, IT SHOULD PAY A MASTERNODE DIRECTLY - if(mnpayments.IsTransactionValid(txNew, nBlockHeight)) { - LogPrint("mnpayments", "IsBlockPayeeValid -- Valid masternode payment at height %d: %s", nBlockHeight, txNew.ToString()); + // If this isn't a superblock or spork15 is activated, check for correct masternode payment + if(mnpayments.IsTransactionValid(txNew, nBlockHeight, blockReward)) { + LogPrint("mnpayments", "%s -- Valid masternode payment at height %d: %s", __func__, nBlockHeight, txNew.ToString()); return true; } if(sporkManager.IsSporkActive(SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT)) { - LogPrintf("IsBlockPayeeValid -- ERROR: Invalid masternode payment detected at height %d: %s", nBlockHeight, txNew.ToString()); + LogPrintf("%s -- ERROR: Invalid masternode payment detected at height %d: %s", __func__, nBlockHeight, txNew.ToString()); return false; } - LogPrintf("IsBlockPayeeValid -- WARNING: Masternode payment enforcement is disabled, accepting any payee\n"); + LogPrintf("%s -- WARNING: Masternode payment enforcement is disabled, accepting any payee\n", __func__); return true; } @@ -196,14 +212,33 @@ void FillBlockPayments(CMutableTransaction& txNew, int nBlockHeight, CAmount blo // (height should be validated inside) if(sporkManager.IsSporkActive(SPORK_9_SUPERBLOCKS_ENABLED) && CSuperblockManager::IsSuperblockTriggered(nBlockHeight)) { - LogPrint("gobject", "FillBlockPayments -- triggered superblock creation at height %d\n", nBlockHeight); - CSuperblockManager::CreateSuperblock(txNew, nBlockHeight, voutSuperblockRet); - return; + LogPrint("gobject", "%s -- triggered superblock creation at height %d\n", __func__, nBlockHeight); + CSuperblockManager::GetSuperblockPayments(nBlockHeight, voutSuperblockRet); + } + + // TODO this is a placeholder until DIP3 is merged, which will allow superblock payments and MN reward payments + // in the same block. We set this to false for now, which means that we'll always get into the next if statement + // when a superblock payment is present + bool allowSuperblockAndMNReward = false; + + // don't allow payments to superblocks AND masternodes before spork15 activation + if (!voutSuperblockRet.empty() && !allowSuperblockAndMNReward) { + txNew.vout.insert(txNew.vout.end(), voutSuperblockRet.begin(), voutSuperblockRet.end()); + return; } - // FILL BLOCK PAYEE WITH MASTERNODE PAYMENT OTHERWISE - mnpayments.FillBlockPayee(txNew, nBlockHeight, blockReward, txoutMasternodeRet); - LogPrint("mnpayments", "FillBlockPayments -- nBlockHeight %d blockReward %lld txoutMasternodeRet %s txNew %s", + if (!mnpayments.GetMasternodeTxOut(nBlockHeight, blockReward, txoutMasternodeRet)) { + // no idea whom to pay (MN list empty?), lets hope for the best + return; + } + + txNew.vout.emplace_back(txoutMasternodeRet); + txNew.vout.insert(txNew.vout.end(), voutSuperblockRet.begin(), voutSuperblockRet.end()); + + // subtract MN payment from miner reward + txNew.vout[0].nValue -= txoutMasternodeRet.nValue; + + LogPrint("mnpayments", "%s -- nBlockHeight %d blockReward %lld txoutMasternodeRet %s txNew %s", __func__, nBlockHeight, blockReward, txoutMasternodeRet.ToString(), txNew.ToString()); } @@ -245,10 +280,10 @@ bool CMasternodePayments::UpdateLastVote(const CMasternodePaymentVote& vote) /** * FillBlockPayee * -* Fill Masternode ONLY payment block +* Get masternode payment tx output */ -void CMasternodePayments::FillBlockPayee(CMutableTransaction& txNew, int nBlockHeight, CAmount blockReward, CTxOut& txoutMasternodeRet) const +bool CMasternodePayments::GetMasternodeTxOut(int nBlockHeight, CAmount blockReward, CTxOut& txoutMasternodeRet) const { // make sure it's not filled yet txoutMasternodeRet = CTxOut(); @@ -261,8 +296,8 @@ void CMasternodePayments::FillBlockPayee(CMutableTransaction& txNew, int nBlockH masternode_info_t mnInfo; if(!mnodeman.GetNextMasternodeInQueueForPayment(nBlockHeight, true, nCount, mnInfo)) { // ...and we can't calculate it on our own - LogPrintf("CMasternodePayments::FillBlockPayee -- Failed to detect masternode to pay\n"); - return; + LogPrintf("CMasternodePayments::%s -- Failed to detect masternode to pay\n", __func__); + return false; } // fill payee with locally calculated winner and hope for the best payee = GetScriptForDestination(mnInfo.keyIDCollateralAddress); @@ -270,18 +305,15 @@ void CMasternodePayments::FillBlockPayee(CMutableTransaction& txNew, int nBlockH // GET MASTERNODE PAYMENT VARIABLES SETUP CAmount masternodePayment = GetMasternodePayment(nBlockHeight, blockReward); - - // split reward between miner ... - txNew.vout[0].nValue -= masternodePayment; - // ... and masternode txoutMasternodeRet = CTxOut(masternodePayment, payee); - txNew.vout.push_back(txoutMasternodeRet); CTxDestination address1; ExtractDestination(payee, address1); CBitcoinAddress address2(address1); - LogPrintf("CMasternodePayments::FillBlockPayee -- Masternode payment %lld to %s\n", masternodePayment, address2.ToString()); + LogPrintf("CMasternodePayments::%s -- Masternode payment %lld to %s\n", __func__, masternodePayment, address2.ToString()); + + return true; } int CMasternodePayments::GetMinMasternodePaymentsProto() const { @@ -446,12 +478,12 @@ bool CMasternodePaymentVote::Sign() uint256 hash = GetSignatureHash(); if(!CHashSigner::SignHash(hash, activeMasternodeInfo.keyMasternode, vchSig)) { - LogPrintf("CMasternodePaymentVote::Sign -- SignHash() failed\n"); + LogPrintf("CMasternodePaymentVote::%s -- SignHash() failed\n", __func__); return false; } if (!CHashSigner::VerifyHash(hash, activeMasternodeInfo.keyIDMasternode, vchSig, strError)) { - LogPrintf("CMasternodePaymentVote::Sign -- VerifyHash() failed, error: %s\n", strError); + LogPrintf("CMasternodePaymentVote::%s -- VerifyHash() failed, error: %s\n", __func__, strError); return false; } } else { @@ -460,12 +492,12 @@ bool CMasternodePaymentVote::Sign() ScriptToAsmStr(payee); if(!CMessageSigner::SignMessage(strMessage, vchSig, activeMasternodeInfo.keyMasternode)) { - LogPrintf("CMasternodePaymentVote::Sign -- SignMessage() failed\n"); + LogPrintf("CMasternodePaymentVote::%s -- SignMessage() failed\n", __func__); return false; } if(!CMessageSigner::VerifyMessage(activeMasternodeInfo.keyIDMasternode, vchSig, strMessage, strError)) { - LogPrintf("CMasternodePaymentVote::Sign -- VerifyMessage() failed, error: %s\n", strError); + LogPrintf("CMasternodePaymentVote::%s -- VerifyMessage() failed, error: %s\n", __func__, strError); return false; } } @@ -519,7 +551,7 @@ bool CMasternodePayments::AddOrUpdatePaymentVote(const CMasternodePaymentVote& v auto it = mapMasternodeBlocks.emplace(vote.nBlockHeight, CMasternodeBlockPayees(vote.nBlockHeight)).first; it->second.AddPayee(vote); - LogPrint("mnpayments", "CMasternodePayments::AddOrUpdatePaymentVote -- added, hash=%s\n", nVoteHash.ToString()); + LogPrint("mnpayments", "CMasternodePayments::%s -- added, hash=%s\n", __func__, nVoteHash.ToString()); return true; } @@ -552,7 +584,7 @@ bool CMasternodeBlockPayees::GetBestPayee(CScript& payeeRet) const LOCK(cs_vecPayees); if(vecPayees.empty()) { - LogPrint("mnpayments", "CMasternodeBlockPayees::GetBestPayee -- ERROR: couldn't find any payee\n"); + LogPrint("mnpayments", "CMasternodeBlockPayees::%s -- ERROR: couldn't find any payee\n", __func__); return false; } @@ -577,7 +609,7 @@ bool CMasternodeBlockPayees::HasPayeeWithVotes(const CScript& payeeIn, int nVote } } - LogPrint("mnpayments", "CMasternodeBlockPayees::HasPayeeWithVotes -- ERROR: couldn't find any payee with %d+ votes\n", nVotesReq); + LogPrint("mnpayments", "CMasternodeBlockPayees::%s -- ERROR: couldn't find any payee with %d+ votes\n", __func__, nVotesReq); return false; } @@ -605,7 +637,7 @@ bool CMasternodeBlockPayees::IsTransactionValid(const CTransaction& txNew) const if (payee.GetVoteCount() >= MNPAYMENTS_SIGNATURES_REQUIRED) { for (const auto& txout : txNew.vout) { if (payee.GetPayee() == txout.scriptPubKey && nMasternodePayment == txout.nValue) { - LogPrint("mnpayments", "CMasternodeBlockPayees::IsTransactionValid -- Found required payment\n"); + LogPrint("mnpayments", "CMasternodeBlockPayees::%s -- Found required payment\n", __func__); return true; } } @@ -622,7 +654,7 @@ bool CMasternodeBlockPayees::IsTransactionValid(const CTransaction& txNew) const } } - LogPrintf("CMasternodeBlockPayees::IsTransactionValid -- ERROR: Missing required payment, possible payees: '%s', amount: %f ABS\n", strPayeesPossible, (float)nMasternodePayment/COIN); + LogPrintf("CMasternodeBlockPayees::%s -- ERROR: Missing required payment, possible payees: '%s', amount: %f ABSOLUTE\n", __func__, strPayeesPossible, (float)nMasternodePayment/COIN); return false; } @@ -658,10 +690,9 @@ std::string CMasternodePayments::GetRequiredPaymentsString(int nBlockHeight) con return it == mapMasternodeBlocks.end() ? "Unknown" : it->second.GetRequiredPaymentsString(); } -bool CMasternodePayments::IsTransactionValid(const CTransaction& txNew, int nBlockHeight) const +bool CMasternodePayments::IsTransactionValid(const CTransaction& txNew, int nBlockHeight, CAmount blockReward) const { LOCK(cs_mapMasternodeBlocks); - const auto it = mapMasternodeBlocks.find(nBlockHeight); return it == mapMasternodeBlocks.end() ? true : it->second.IsTransactionValid(txNew); } @@ -679,14 +710,14 @@ void CMasternodePayments::CheckAndRemove() CMasternodePaymentVote vote = (*it).second; if(nCachedBlockHeight - vote.nBlockHeight > nLimit) { - LogPrint("mnpayments", "CMasternodePayments::CheckAndRemove -- Removing old Masternode payment: nBlockHeight=%d\n", vote.nBlockHeight); + LogPrint("mnpayments", "CMasternodePayments::%s -- Removing old Masternode payment: nBlockHeight=%d\n", __func__, vote.nBlockHeight); mapMasternodePaymentVotes.erase(it++); mapMasternodeBlocks.erase(vote.nBlockHeight); } else { ++it; } } - LogPrintf("CMasternodePayments::CheckAndRemove -- %s\n", ToString()); + LogPrintf("CMasternodePayments::%s -- %s\n", __func__, ToString()); } bool CMasternodePaymentVote::IsValid(CNode* pnode, int nValidationHeight, std::string& strError, CConnman& connman) const @@ -724,7 +755,7 @@ bool CMasternodePaymentVote::IsValid(CNode* pnode, int nValidationHeight, std::s int nRank; if(!mnodeman.GetMasternodeRank(masternodeOutpoint, nRank, nBlockHeight - 101, nMinRequiredProtocol)) { - LogPrint("mnpayments", "CMasternodePaymentVote::IsValid -- Can't calculate rank for masternode %s\n", + LogPrint("mnpayments", "CMasternodePaymentVote::%s -- Can't calculate rank for masternode %s\n", __func__, masternodeOutpoint.ToStringShort()); return false; } @@ -737,7 +768,7 @@ bool CMasternodePaymentVote::IsValid(CNode* pnode, int nValidationHeight, std::s if(nRank > MNPAYMENTS_SIGNATURES_TOTAL*2 && nBlockHeight > nValidationHeight) { LOCK(cs_main); strError = strprintf("Masternode %s is not in the top %d (%d)", masternodeOutpoint.ToStringShort(), MNPAYMENTS_SIGNATURES_TOTAL*2, nRank); - LogPrintf("CMasternodePaymentVote::IsValid -- Error: %s\n", strError); + LogPrintf("CMasternodePaymentVote::%s -- Error: %s\n", __func__, strError); Misbehaving(pnode->GetId(), 20); } // Still invalid however @@ -761,30 +792,30 @@ bool CMasternodePayments::ProcessBlock(int nBlockHeight, CConnman& connman) int nRank; if (!mnodeman.GetMasternodeRank(activeMasternodeInfo.outpoint, nRank, nBlockHeight - 101, GetMinMasternodePaymentsProto())) { - LogPrint("mnpayments", "CMasternodePayments::ProcessBlock -- Unknown Masternode\n"); + LogPrint("mnpayments", "CMasternodePayments::%s -- Unknown Masternode\n", __func__); return false; } if (nRank > MNPAYMENTS_SIGNATURES_TOTAL) { - LogPrint("mnpayments", "CMasternodePayments::ProcessBlock -- Masternode not in the top %d (%d)\n", MNPAYMENTS_SIGNATURES_TOTAL, nRank); + LogPrint("mnpayments", "CMasternodePayments::%s -- Masternode not in the top %d (%d)\n", __func__, MNPAYMENTS_SIGNATURES_TOTAL, nRank); return false; } // LOCATE THE NEXT MASTERNODE WHICH SHOULD BE PAID - LogPrintf("CMasternodePayments::ProcessBlock -- Start: nBlockHeight=%d, masternode=%s\n", nBlockHeight, activeMasternodeInfo.outpoint.ToStringShort()); + LogPrintf("CMasternodePayments::%s -- Start: nBlockHeight=%d, masternode=%s\n", __func__, nBlockHeight, activeMasternodeInfo.outpoint.ToStringShort()); // pay to the oldest MN that still had no payment but its input is old enough and it was active long enough int nCount = 0; masternode_info_t mnInfo; if (!mnodeman.GetNextMasternodeInQueueForPayment(nBlockHeight, true, nCount, mnInfo)) { - LogPrintf("CMasternodePayments::ProcessBlock -- ERROR: Failed to find masternode to pay\n"); + LogPrintf("CMasternodePayments::%s -- ERROR: Failed to find masternode to pay\n", __func__); return false; } - LogPrintf("CMasternodePayments::ProcessBlock -- Masternode found by GetNextMasternodeInQueueForPayment(): %s\n", mnInfo.outpoint.ToStringShort()); + LogPrintf("CMasternodePayments::%s -- Masternode found by GetNextMasternodeInQueueForPayment(): %s\n", __func__, mnInfo.outpoint.ToStringShort()); CScript payee = GetScriptForDestination(mnInfo.keyIDCollateralAddress); @@ -795,13 +826,13 @@ bool CMasternodePayments::ProcessBlock(int nBlockHeight, CConnman& connman) ExtractDestination(payee, address1); CBitcoinAddress address2(address1); - LogPrintf("CMasternodePayments::ProcessBlock -- vote: payee=%s, nBlockHeight=%d\n", address2.ToString(), nBlockHeight); + LogPrintf("CMasternodePayments::%s -- vote: payee=%s, nBlockHeight=%d\n", address2.ToString(), nBlockHeight); // SIGN MESSAGE TO NETWORK WITH OUR MASTERNODE KEYS - LogPrintf("CMasternodePayments::ProcessBlock -- Signing vote\n"); + LogPrintf("CMasternodePayments::%s -- Signing vote\n", __func__); if (voteNew.Sign()) { - LogPrintf("CMasternodePayments::ProcessBlock -- AddOrUpdatePaymentVote()\n"); + LogPrintf("CMasternodePayments::%s -- AddOrUpdatePaymentVote()\n", __func__); if (AddOrUpdatePaymentVote(voteNew)) { voteNew.Relay(connman); @@ -818,13 +849,13 @@ void CMasternodePayments::CheckBlockVotes(int nBlockHeight) CMasternodeMan::rank_pair_vec_t mns; if (!mnodeman.GetMasternodeRanks(mns, nBlockHeight - 101, GetMinMasternodePaymentsProto())) { - LogPrintf("CMasternodePayments::CheckBlockVotes -- nBlockHeight=%d, GetMasternodeRanks failed\n", nBlockHeight); + LogPrintf("CMasternodePayments::%s -- nBlockHeight=%d, GetMasternodeRanks failed\n", __func__, nBlockHeight); return; } std::string debugStr; - debugStr += strprintf("CMasternodePayments::CheckBlockVotes -- nBlockHeight=%d,\n Expected voting MNs:\n", nBlockHeight); + debugStr += strprintf("CMasternodePayments::%s -- nBlockHeight=%d,\n Expected voting MNs:\n", __func__, nBlockHeight); LOCK2(cs_mapMasternodeBlocks, cs_mapMasternodePaymentVotes); @@ -886,7 +917,7 @@ void CMasternodePaymentVote::Relay(CConnman& connman) const { // Do not relay until fully synced if(!masternodeSync.IsSynced()) { - LogPrint("mnpayments", "CMasternodePayments::Relay -- won't relay until fully synced\n"); + LogPrint("mnpayments", "CMasternodePayments::%s -- won't relay until fully synced\n", __func__); return; } @@ -975,7 +1006,7 @@ void CMasternodePayments::Sync(CNode* pnode, CConnman& connman) const } } - LogPrintf("CMasternodePayments::Sync -- Sent %d votes to peer=%d\n", nInvCount, pnode->id); + LogPrintf("CMasternodePayments::%s -- Sent %d votes to peer=%d\n", __func__, nInvCount, pnode->id); CNetMsgMaker msgMaker(pnode->GetSendVersion()); connman.PushMessage(pnode, msgMaker.Make(NetMsgType::SYNCSTATUSCOUNT, MASTERNODE_SYNC_MNW, nInvCount)); } @@ -1000,7 +1031,7 @@ void CMasternodePayments::RequestLowDataPaymentBlocks(CNode* pnode, CConnman& co vToFetch.push_back(CInv(MSG_MASTERNODE_PAYMENT_BLOCK, pindex->GetBlockHash())); // We should not violate GETDATA rules if(vToFetch.size() == MAX_INV_SZ) { - LogPrintf("CMasternodePayments::RequestLowDataPaymentBlocks -- asking peer=%d for %d blocks\n", pnode->id, MAX_INV_SZ); + LogPrintf("CMasternodePayments::%s -- asking peer=%d for %d blocks\n", __func__, pnode->id, MAX_INV_SZ); connman.PushMessage(pnode, msgMaker.Make(NetMsgType::GETDATA, vToFetch)); // Start filling new batch vToFetch.clear(); @@ -1046,7 +1077,7 @@ void CMasternodePayments::RequestLowDataPaymentBlocks(CNode* pnode, CConnman& co } // We should not violate GETDATA rules if(vToFetch.size() == MAX_INV_SZ) { - LogPrintf("CMasternodePayments::RequestLowDataPaymentBlocks -- asking peer=%d for %d payment blocks\n", pnode->id, MAX_INV_SZ); + LogPrintf("CMasternodePayments::%s -- asking peer=%d for %d payment blocks\n", __func__, pnode->id, MAX_INV_SZ); connman.PushMessage(pnode, msgMaker.Make(NetMsgType::GETDATA, vToFetch)); // Start filling new batch vToFetch.clear(); @@ -1054,7 +1085,7 @@ void CMasternodePayments::RequestLowDataPaymentBlocks(CNode* pnode, CConnman& co } // Ask for the rest of it if(!vToFetch.empty()) { - LogPrintf("CMasternodePayments::RequestLowDataPaymentBlocks -- asking peer=%d for %d payment blocks\n", pnode->id, vToFetch.size()); + LogPrintf("CMasternodePayments::%s -- asking peer=%d for %d payment blocks\n", __func__, pnode->id, vToFetch.size()); connman.PushMessage(pnode, msgMaker.Make(NetMsgType::GETDATA, vToFetch)); } } @@ -1086,7 +1117,7 @@ void CMasternodePayments::UpdatedBlockTip(const CBlockIndex *pindex, CConnman& c if(!pindex) return; nCachedBlockHeight = pindex->nHeight; - LogPrint("mnpayments", "CMasternodePayments::UpdatedBlockTip -- nCachedBlockHeight=%d\n", nCachedBlockHeight); + LogPrint("mnpayments", "CMasternodePayments::%s -- nCachedBlockHeight=%d\n", __func__, nCachedBlockHeight); int nFutureBlock = nCachedBlockHeight + 10; diff --git a/src/masternode-payments.h b/src/masternode-payments.h index 48ea3737a4da..1d6141fe8314 100644 --- a/src/masternode-payments.h +++ b/src/masternode-payments.h @@ -215,7 +215,7 @@ class CMasternodePayments void CheckAndRemove(); bool GetBlockPayee(int nBlockHeight, CScript& payeeRet) const; - bool IsTransactionValid(const CTransaction& txNew, int nBlockHeight) const; + bool IsTransactionValid(const CTransaction& txNew, int nBlockHeight, CAmount blockReward) const; bool IsScheduled(const masternode_info_t& mnInfo, int nNotBlockHeight) const; bool UpdateLastVote(const CMasternodePaymentVote& vote); @@ -223,7 +223,7 @@ class CMasternodePayments int GetMinMasternodePaymentsProto() const; void ProcessMessage(CNode* pfrom, const std::string& strCommand, CDataStream& vRecv, CConnman& connman); std::string GetRequiredPaymentsString(int nBlockHeight) const; - void FillBlockPayee(CMutableTransaction& txNew, int nBlockHeight, CAmount blockReward, CTxOut& txoutMasternodeRet) const; + bool GetMasternodeTxOut(int nBlockHeight, CAmount blockReward, CTxOut& txoutMasternodeRet) const; std::string ToString() const; int GetBlockCount() const { return mapMasternodeBlocks.size(); } From 7fd2c466937b63aa56477ad387af82aee238dd66 Mon Sep 17 00:00:00 2001 From: Alexander Block Date: Mon, 13 Aug 2018 18:07:52 +0200 Subject: [PATCH 040/282] Backport Bitcoin bitcoin#11881: Remove Python2 support * Merge bitcoin#11881: Remove Python2 support 1874058 Make base58 python contrib code work with python3 (Evan Klitzke) bc6fdf2 Change all python files to use Python3 (John Newbery) Pull request description: Following discussion here: bitcoin#11843 (comment) It's easier for maintainers if all python tools/scripts support only a single version of Python. There are only a few scripts that aren't explicitly python3 at this point, so this PR changes those remaining scripts to explicitly require python3. Tree-SHA512: 5d38eef6e0fc7d8515e23a1f4c75e8b4160fd0fe23cba52a1f41689b114e54a9e503e0724829e8b41982ef98f2d113df80d9e238213b74f09ceaed0344a19e24 * Merge bitcoin#12829: Python3 fixup f50975b [contrib] fixup symbol-check.py Python3 support (John Newbery) 5de2b18 [contrib] fixup security-check.py Python3 support (John Newbery) Pull request description: security-check.py and symbol-check.py were broken by bitcoin#11881. Fix them. --- contrib/devtools/check-doc.py | 24 ++++---- contrib/devtools/clang-format-diff.py | 19 +++--- contrib/devtools/optimize-pngs.py | 40 ++++++------- contrib/devtools/security-check.py | 47 ++++++++------- contrib/devtools/symbol-check.py | 69 +++++++++++----------- contrib/devtools/update-translations.py | 3 +- contrib/macdeploy/custom_dsstore.py | 4 +- contrib/macdeploy/macdeployqtplus | 34 +++-------- contrib/testgen/base58.py | 20 ++++--- contrib/testgen/gen_base58_test_vectors.py | 25 ++++---- share/qt/extract_strings_qt.py | 3 +- share/rpcuser/rpcuser.py | 2 +- 12 files changed, 138 insertions(+), 152 deletions(-) diff --git a/contrib/devtools/check-doc.py b/contrib/devtools/check-doc.py index fa1e137587a6..464e2a8a46b6 100644 --- a/contrib/devtools/check-doc.py +++ b/contrib/devtools/check-doc.py @@ -1,4 +1,4 @@ -#!/usr/bin/env python +#!/usr/bin/env python3 # 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. @@ -15,29 +15,29 @@ FOLDER_GREP = 'src' FOLDER_TEST = 'src/test/' -CMD_ROOT_DIR = '`git rev-parse --show-toplevel`/%s' % FOLDER_GREP -CMD_GREP_ARGS = r"egrep -r -I '(map(Multi)?Args(\.count\(|\[)|Get(Bool)?Arg\()\"\-[^\"]+?\"' %s | grep -v '%s'" % (CMD_ROOT_DIR, FOLDER_TEST) -CMD_GREP_DOCS = r"egrep -r -I 'HelpMessageOpt\(\"\-[^\"=]+?(=|\")' %s" % (CMD_ROOT_DIR) +CMD_ROOT_DIR = '`git rev-parse --show-toplevel`/{}'.format(FOLDER_GREP) +CMD_GREP_ARGS = r"egrep -r -I '(map(Multi)?Args(\.count\(|\[)|Get(Bool)?Arg\()\"\-[^\"]+?\"' {} | grep -v '{}'".format(CMD_ROOT_DIR, FOLDER_TEST) +CMD_GREP_DOCS = r"egrep -r -I 'HelpMessageOpt\(\"\-[^\"=]+?(=|\")' {}".format(CMD_ROOT_DIR) REGEX_ARG = re.compile(r'(?:map(?:Multi)?Args(?:\.count\(|\[)|Get(?:Bool)?Arg\()\"(\-[^\"]+?)\"') REGEX_DOC = re.compile(r'HelpMessageOpt\(\"(\-[^\"=]+?)(?:=|\")') # list unsupported, deprecated and duplicate args as they need no documentation SET_DOC_OPTIONAL = set(['-rpcssl', '-benchmark', '-h', '-help', '-socks', '-tor', '-debugnet', '-whitelistalwaysrelay', '-blockminsize']) def main(): - used = check_output(CMD_GREP_ARGS, shell=True) - docd = check_output(CMD_GREP_DOCS, shell=True) + used = check_output(CMD_GREP_ARGS, shell=True, universal_newlines=True) + docd = check_output(CMD_GREP_DOCS, shell=True, universal_newlines=True) args_used = set(re.findall(REGEX_ARG,used)) args_docd = set(re.findall(REGEX_DOC,docd)).union(SET_DOC_OPTIONAL) args_need_doc = args_used.difference(args_docd) args_unknown = args_docd.difference(args_used) - print "Args used : %s" % len(args_used) - print "Args documented : %s" % len(args_docd) - print "Args undocumented: %s" % len(args_need_doc) - print args_need_doc - print "Args unknown : %s" % len(args_unknown) - print args_unknown + print("Args used : {}".format(len(args_used))) + print("Args documented : {}".format(len(args_docd))) + print("Args undocumented: {}".format(len(args_need_doc))) + print(args_need_doc) + print("Args unknown : {}".format(len(args_unknown))) + print(args_unknown) exit(len(args_need_doc)) diff --git a/contrib/devtools/clang-format-diff.py b/contrib/devtools/clang-format-diff.py index 7ea49b65e177..ca1bd8854fc6 100644 --- a/contrib/devtools/clang-format-diff.py +++ b/contrib/devtools/clang-format-diff.py @@ -1,4 +1,4 @@ -#!/usr/bin/env python +#!/usr/bin/env python3 # #===- clang-format-diff.py - ClangFormat Diff Reformatter ----*- python -*--===# # @@ -69,10 +69,10 @@ import argparse import difflib +import io import re import string import subprocess -import StringIO import sys @@ -133,9 +133,9 @@ def main(): ['-lines', str(start_line) + ':' + str(end_line)]) # Reformat files containing changes in place. - for filename, lines in lines_by_file.iteritems(): + for filename, lines in lines_by_file.items(): if args.i and args.verbose: - print 'Formatting', filename + print('Formatting {}'.format(filename)) command = [binary, filename] if args.i: command.append('-i') @@ -143,8 +143,11 @@ def main(): command.append('-sort-includes') command.extend(lines) command.extend(['-style=file', '-fallback-style=none']) - p = subprocess.Popen(command, stdout=subprocess.PIPE, - stderr=None, stdin=subprocess.PIPE) + p = subprocess.Popen(command, + stdout=subprocess.PIPE, + stderr=None, + stdin=subprocess.PIPE, + universal_newlines=True) stdout, stderr = p.communicate() if p.returncode != 0: sys.exit(p.returncode) @@ -152,11 +155,11 @@ def main(): if not args.i: with open(filename) as f: code = f.readlines() - formatted_code = StringIO.StringIO(stdout).readlines() + formatted_code = io.StringIO(stdout).readlines() diff = difflib.unified_diff(code, formatted_code, filename, filename, '(before formatting)', '(after formatting)') - diff_string = string.join(diff, '') + diff_string = ''.join(diff) if len(diff_string) > 0: sys.stdout.write(diff_string) diff --git a/contrib/devtools/optimize-pngs.py b/contrib/devtools/optimize-pngs.py index 6086533cdee1..32c136f4626e 100755 --- a/contrib/devtools/optimize-pngs.py +++ b/contrib/devtools/optimize-pngs.py @@ -1,4 +1,4 @@ -#!/usr/bin/env python +#!/usr/bin/env python3 # 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. @@ -10,7 +10,7 @@ import sys import subprocess import hashlib -from PIL import Image +from PIL import Image # pip3 install Pillow def file_hash(filename): '''Return hash of raw file contents''' @@ -26,8 +26,8 @@ def content_hash(filename): pngcrush = 'pngcrush' git = 'git' -folders = ["src/qt/res/movies", "src/qt/res/icons", "src/qt/res/icons/crownium", "src/qt/res/icons/drkblue", "src/qt/res/icons/light", "src/qt/res/icons/trad", "src/qt/res/images", "src/qt/res/images/crownium", "src/qt/res/images/drkblue", "src/qt/res/images/light", "src/qt/res/images/trad", "share/pixmaps"] -basePath = subprocess.check_output([git, 'rev-parse', '--show-toplevel']).rstrip('\n') +folders = ["src/qt/res/movies", "src/qt/res/icons", "src/qt/res/icons/crownium", "src/qt/res/icons/drkblue", "src/qt/res/icons/light", "src/qt/res/icons/light-retro", "src/qt/res/icons/trad", "src/qt/res/images", "src/qt/res/images/crownium", "src/qt/res/images/drkblue", "src/qt/res/images/light", "src/qt/res/images/light-retro", "src/qt/res/images/trad", "share/pixmaps"] +basePath = subprocess.check_output([git, 'rev-parse', '--show-toplevel'], universal_newlines=True).rstrip('\n') totalSaveBytes = 0 noHashChange = True @@ -37,42 +37,40 @@ def content_hash(filename): for file in os.listdir(absFolder): extension = os.path.splitext(file)[1] if extension.lower() == '.png': - print("optimizing "+file+"..."), + print("optimizing {}...".format(file), end =' ') file_path = os.path.join(absFolder, file) fileMetaMap = {'file' : file, 'osize': os.path.getsize(file_path), 'sha256Old' : file_hash(file_path)} fileMetaMap['contentHashPre'] = content_hash(file_path) - - pngCrushOutput = "" + try: - pngCrushOutput = subprocess.check_output( - [pngcrush, "-brute", "-ow", "-rem", "gAMA", "-rem", "cHRM", "-rem", "iCCP", "-rem", "sRGB", "-rem", "alla", "-rem", "text", file_path], - stderr=subprocess.STDOUT).rstrip('\n') + subprocess.call([pngcrush, "-brute", "-ow", "-rem", "gAMA", "-rem", "cHRM", "-rem", "iCCP", "-rem", "sRGB", "-rem", "alla", "-rem", "text", file_path], + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) except: - print "pngcrush is not installed, aborting..." + print("pngcrush is not installed, aborting...") sys.exit(0) - + #verify - if "Not a PNG file" in subprocess.check_output([pngcrush, "-n", "-v", file_path], stderr=subprocess.STDOUT): - print "PNG file "+file+" is corrupted after crushing, check out pngcursh version" + if "Not a PNG file" in subprocess.check_output([pngcrush, "-n", "-v", file_path], stderr=subprocess.STDOUT, universal_newlines=True): + print("PNG file "+file+" is corrupted after crushing, check out pngcursh version") sys.exit(1) - + fileMetaMap['sha256New'] = file_hash(file_path) fileMetaMap['contentHashPost'] = content_hash(file_path) if fileMetaMap['contentHashPre'] != fileMetaMap['contentHashPost']: - print "Image contents of PNG file "+file+" before and after crushing don't match" + print("Image contents of PNG file {} before and after crushing don't match".format(file)) sys.exit(1) fileMetaMap['psize'] = os.path.getsize(file_path) outputArray.append(fileMetaMap) - print("done\n"), + print("done") -print "summary:\n+++++++++++++++++" +print("summary:\n+++++++++++++++++") for fileDict in outputArray: oldHash = fileDict['sha256Old'] newHash = fileDict['sha256New'] totalSaveBytes += fileDict['osize'] - fileDict['psize'] noHashChange = noHashChange and (oldHash == newHash) - print fileDict['file']+"\n size diff from: "+str(fileDict['osize'])+" to: "+str(fileDict['psize'])+"\n old sha256: "+oldHash+"\n new sha256: "+newHash+"\n" - -print "completed. Checksum stable: "+str(noHashChange)+". Total reduction: "+str(totalSaveBytes)+" bytes" + print(fileDict['file']+"\n size diff from: "+str(fileDict['osize'])+" to: "+str(fileDict['psize'])+"\n old sha256: "+oldHash+"\n new sha256: "+newHash+"\n") + +print("completed. Checksum stable: "+str(noHashChange)+". Total reduction: "+str(totalSaveBytes)+" bytes") diff --git a/contrib/devtools/security-check.py b/contrib/devtools/security-check.py index c90541e27119..aa73bc61d0ec 100755 --- a/contrib/devtools/security-check.py +++ b/contrib/devtools/security-check.py @@ -1,4 +1,4 @@ -#!/usr/bin/env python +#!/usr/bin/env python3 # Copyright (c) 2015-2016 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. @@ -8,7 +8,6 @@ Otherwise the exit status will be 1 and it will log which executables failed which checks. Needs `readelf` (for ELF) and `objdump` (for PE). ''' -from __future__ import division,print_function,unicode_literals import subprocess import sys import os @@ -21,38 +20,38 @@ def check_ELF_PIE(executable): ''' Check for position independent executable (PIE), allowing for address space randomization. ''' - p = subprocess.Popen([READELF_CMD, '-h', '-W', executable], stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE) + p = subprocess.Popen([READELF_CMD, '-h', '-W', executable], stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE, universal_newlines=True) (stdout, stderr) = p.communicate() if p.returncode: raise IOError('Error opening file') ok = False - for line in stdout.split(b'\n'): + for line in stdout.splitlines(): line = line.split() - if len(line)>=2 and line[0] == b'Type:' and line[1] == b'DYN': + if len(line)>=2 and line[0] == 'Type:' and line[1] == 'DYN': ok = True return ok def get_ELF_program_headers(executable): '''Return type and flags for ELF program headers''' - p = subprocess.Popen([READELF_CMD, '-l', '-W', executable], stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE) + p = subprocess.Popen([READELF_CMD, '-l', '-W', executable], stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE, universal_newlines=True) (stdout, stderr) = p.communicate() if p.returncode: raise IOError('Error opening file') in_headers = False count = 0 headers = [] - for line in stdout.split(b'\n'): - if line.startswith(b'Program Headers:'): + for line in stdout.splitlines(): + if line.startswith('Program Headers:'): in_headers = True - if line == b'': + if line == '': in_headers = False if in_headers: if count == 1: # header line - ofs_typ = line.find(b'Type') - ofs_offset = line.find(b'Offset') - ofs_flags = line.find(b'Flg') - ofs_align = line.find(b'Align') + ofs_typ = line.find('Type') + ofs_offset = line.find('Offset') + ofs_flags = line.find('Flg') + ofs_align = line.find('Align') if ofs_typ == -1 or ofs_offset == -1 or ofs_flags == -1 or ofs_align == -1: raise ValueError('Cannot parse elfread -lW output') elif count > 1: @@ -69,9 +68,9 @@ def check_ELF_NX(executable): have_wx = False have_gnu_stack = False for (typ, flags) in get_ELF_program_headers(executable): - if typ == b'GNU_STACK': + if typ == 'GNU_STACK': have_gnu_stack = True - if b'W' in flags and b'E' in flags: # section is both writable and executable + if 'W' in flags and 'E' in flags: # section is both writable and executable have_wx = True return have_gnu_stack and not have_wx @@ -88,17 +87,17 @@ def check_ELF_RELRO(executable): # However, the dynamic linker need to write to this area so these are RW. # Glibc itself takes care of mprotecting this area R after relocations are finished. # See also http://permalink.gmane.org/gmane.comp.gnu.binutils/71347 - if typ == b'GNU_RELRO': + if typ == 'GNU_RELRO': have_gnu_relro = True have_bindnow = False - p = subprocess.Popen([READELF_CMD, '-d', '-W', executable], stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE) + p = subprocess.Popen([READELF_CMD, '-d', '-W', executable], stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE, universal_newlines=True) (stdout, stderr) = p.communicate() if p.returncode: raise IOError('Error opening file') - for line in stdout.split(b'\n'): + for line in stdout.splitlines(): tokens = line.split() - if len(tokens)>1 and tokens[1] == b'(BIND_NOW)' or (len(tokens)>2 and tokens[1] == b'(FLAGS)' and b'BIND_NOW' in tokens[2]): + if len(tokens)>1 and tokens[1] == '(BIND_NOW)' or (len(tokens)>2 and tokens[1] == '(FLAGS)' and 'BIND_NOW' in tokens[2]): have_bindnow = True return have_gnu_relro and have_bindnow @@ -106,13 +105,13 @@ def check_ELF_Canary(executable): ''' Check for use of stack canary ''' - p = subprocess.Popen([READELF_CMD, '--dyn-syms', '-W', executable], stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE) + p = subprocess.Popen([READELF_CMD, '--dyn-syms', '-W', executable], stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE, universal_newlines=True) (stdout, stderr) = p.communicate() if p.returncode: raise IOError('Error opening file') ok = False - for line in stdout.split(b'\n'): - if b'__stack_chk_fail' in line: + for line in stdout.splitlines(): + if '__stack_chk_fail' in line: ok = True return ok @@ -122,13 +121,13 @@ def get_PE_dll_characteristics(executable): Returns a tuple (arch,bits) where arch is 'i386:x86-64' or 'i386' and bits is the DllCharacteristics value. ''' - p = subprocess.Popen([OBJDUMP_CMD, '-x', executable], stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE) + p = subprocess.Popen([OBJDUMP_CMD, '-x', executable], stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE, universal_newlines=True) (stdout, stderr) = p.communicate() if p.returncode: raise IOError('Error opening file') arch = '' bits = 0 - for line in stdout.split('\n'): + for line in stdout.splitlines(): tokens = line.split() if len(tokens)>=2 and tokens[0] == 'architecture:': arch = tokens[1].rstrip(',') diff --git a/contrib/devtools/symbol-check.py b/contrib/devtools/symbol-check.py index 8f8685006e11..c23ee5624c00 100755 --- a/contrib/devtools/symbol-check.py +++ b/contrib/devtools/symbol-check.py @@ -1,4 +1,4 @@ -#!/usr/bin/env python +#!/usr/bin/env python3 # Copyright (c) 2014 Wladimir J. van der Laan # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. @@ -11,7 +11,6 @@ find ../gitian-builder/build -type f -executable | xargs python contrib/devtools/symbol-check.py ''' -from __future__ import division, print_function, unicode_literals import subprocess import re import sys @@ -47,28 +46,28 @@ # Ignore symbols that are exported as part of every executable IGNORE_EXPORTS = { -b'_edata', b'_end', b'_init', b'__bss_start', b'_fini', b'_IO_stdin_used' +'_edata', '_end', '_init', '__bss_start', '_fini', '_IO_stdin_used' } READELF_CMD = os.getenv('READELF', '/usr/bin/readelf') CPPFILT_CMD = os.getenv('CPPFILT', '/usr/bin/c++filt') # Allowed NEEDED libraries ALLOWED_LIBRARIES = { # bitcoind and bitcoin-qt -b'libgcc_s.so.1', # GCC base support -b'libc.so.6', # C library -b'libpthread.so.0', # threading -b'libanl.so.1', # DNS resolve -b'libm.so.6', # math library -b'librt.so.1', # real-time (clock) -b'ld-linux-x86-64.so.2', # 64-bit dynamic linker -b'ld-linux.so.2', # 32-bit dynamic linker +'libgcc_s.so.1', # GCC base support +'libc.so.6', # C library +'libpthread.so.0', # threading +'libanl.so.1', # DNS resolve +'libm.so.6', # math library +'librt.so.1', # real-time (clock) +'ld-linux-x86-64.so.2', # 64-bit dynamic linker +'ld-linux.so.2', # 32-bit dynamic linker # bitcoin-qt only -b'libX11-xcb.so.1', # part of X11 -b'libX11.so.6', # part of X11 -b'libxcb.so.1', # part of X11 -b'libfontconfig.so.1', # font support -b'libfreetype.so.6', # font parsing -b'libdl.so.2' # programming interface to dynamic linker +'libX11-xcb.so.1', # part of X11 +'libX11.so.6', # part of X11 +'libxcb.so.1', # part of X11 +'libfontconfig.so.1', # font support +'libfreetype.so.6', # font parsing +'libdl.so.2' # programming interface to dynamic linker } class CPPFilt(object): @@ -78,10 +77,10 @@ class CPPFilt(object): Use a pipe to the 'c++filt' command. ''' def __init__(self): - self.proc = subprocess.Popen(CPPFILT_CMD, stdin=subprocess.PIPE, stdout=subprocess.PIPE) + self.proc = subprocess.Popen(CPPFILT_CMD, stdin=subprocess.PIPE, stdout=subprocess.PIPE, universal_newlines=True) def __call__(self, mangled): - self.proc.stdin.write(mangled + b'\n') + self.proc.stdin.write(mangled + '\n') self.proc.stdin.flush() return self.proc.stdout.readline().rstrip() @@ -95,43 +94,43 @@ def read_symbols(executable, imports=True): Parse an ELF executable and return a list of (symbol,version) tuples for dynamic, imported symbols. ''' - p = subprocess.Popen([READELF_CMD, '--dyn-syms', '-W', executable], stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE) + p = subprocess.Popen([READELF_CMD, '--dyn-syms', '-W', executable], stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE, universal_newlines=True) (stdout, stderr) = p.communicate() if p.returncode: raise IOError('Could not read symbols for %s: %s' % (executable, stderr.strip())) syms = [] - for line in stdout.split(b'\n'): + for line in stdout.splitlines(): line = line.split() - if len(line)>7 and re.match(b'[0-9]+:$', line[0]): - (sym, _, version) = line[7].partition(b'@') - is_import = line[6] == b'UND' - if version.startswith(b'@'): + if len(line)>7 and re.match('[0-9]+:$', line[0]): + (sym, _, version) = line[7].partition('@') + is_import = line[6] == 'UND' + if version.startswith('@'): version = version[1:] if is_import == imports: syms.append((sym, version)) return syms def check_version(max_versions, version): - if b'_' in version: - (lib, _, ver) = version.rpartition(b'_') + if '_' in version: + (lib, _, ver) = version.rpartition('_') else: lib = version ver = '0' - ver = tuple([int(x) for x in ver.split(b'.')]) + ver = tuple([int(x) for x in ver.split('.')]) if not lib in max_versions: return False return ver <= max_versions[lib] def read_libraries(filename): - p = subprocess.Popen([READELF_CMD, '-d', '-W', filename], stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE) + p = subprocess.Popen([READELF_CMD, '-d', '-W', filename], stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE, universal_newlines=True) (stdout, stderr) = p.communicate() if p.returncode: raise IOError('Error opening file') libraries = [] - for line in stdout.split(b'\n'): + for line in stdout.splitlines(): tokens = line.split() - if len(tokens)>2 and tokens[1] == b'(NEEDED)': - match = re.match(b'^Shared library: \[(.*)\]$', b' '.join(tokens[2:])) + if len(tokens)>2 and tokens[1] == '(NEEDED)': + match = re.match('^Shared library: \[(.*)\]$', ' '.join(tokens[2:])) if match: libraries.append(match.group(1)) else: @@ -145,18 +144,18 @@ def read_libraries(filename): # Check imported symbols for sym,version in read_symbols(filename, True): if version and not check_version(MAX_VERSIONS, version): - print('%s: symbol %s from unsupported version %s' % (filename, cppfilt(sym).decode('utf-8'), version.decode('utf-8'))) + print('%s: symbol %s from unsupported version %s' % (filename, cppfilt(sym), version)) retval = 1 # Check exported symbols for sym,version in read_symbols(filename, False): if sym in IGNORE_EXPORTS: continue - print('%s: export of symbol %s not allowed' % (filename, cppfilt(sym).decode('utf-8'))) + print('%s: export of symbol %s not allowed' % (filename, cppfilt(sym))) retval = 1 # Check dependency libraries for library_name in read_libraries(filename): if library_name not in ALLOWED_LIBRARIES: - print('%s: NEEDED library %s is not allowed' % (filename, library_name.decode('utf-8'))) + print('%s: NEEDED library %s is not allowed' % (filename, library_name)) retval = 1 exit(retval) diff --git a/contrib/devtools/update-translations.py b/contrib/devtools/update-translations.py index a61c19c1cdf2..5a4d49aff4c5 100755 --- a/contrib/devtools/update-translations.py +++ b/contrib/devtools/update-translations.py @@ -1,4 +1,4 @@ -#!/usr/bin/env python +#!/usr/bin/env python3 # Copyright (c) 2014 Wladimir J. van der Laan # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. @@ -15,7 +15,6 @@ TODO: - auto-add new translations to the build system according to the translation process ''' -from __future__ import division, print_function import subprocess import re import sys diff --git a/contrib/macdeploy/custom_dsstore.py b/contrib/macdeploy/custom_dsstore.py index ffa32a53b66c..9684b5a67eb5 100644 --- a/contrib/macdeploy/custom_dsstore.py +++ b/contrib/macdeploy/custom_dsstore.py @@ -1,9 +1,7 @@ -#!/usr/bin/env python +#!/usr/bin/env python3 # Copyright (c) 2013-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. - -from __future__ import division,print_function,unicode_literals import biplist from ds_store import DSStore from mac_alias import Alias diff --git a/contrib/macdeploy/macdeployqtplus b/contrib/macdeploy/macdeployqtplus index f7216c02fb51..51914c6329d5 100755 --- a/contrib/macdeploy/macdeployqtplus +++ b/contrib/macdeploy/macdeployqtplus @@ -1,6 +1,4 @@ -#!/usr/bin/env python - -from __future__ import division, print_function, unicode_literals +#!/usr/bin/env python3 # # Copyright (C) 2011 Patrick "p2k" Schneider # @@ -204,7 +202,7 @@ def getFrameworks(binaryPath, verbose): if verbose >= 3: print("Inspecting with otool: " + binaryPath) otoolbin=os.getenv("OTOOL", "otool") - otool = subprocess.Popen([otoolbin, "-L", binaryPath], stdout=subprocess.PIPE, stderr=subprocess.PIPE) + otool = subprocess.Popen([otoolbin, "-L", binaryPath], stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True) o_stdout, o_stderr = otool.communicate() if otool.returncode != 0: if verbose >= 1: @@ -212,7 +210,7 @@ def getFrameworks(binaryPath, verbose): sys.stderr.flush() raise RuntimeError("otool failed with return code %d" % otool.returncode) - otoolLines = o_stdout.decode().split("\n") + otoolLines = o_stdout.split("\n") otoolLines.pop(0) # First line is the inspected binary if ".framework" in binaryPath or binaryPath.endswith(".dylib"): otoolLines.pop(0) # Frameworks and dylibs list themselves as a dependency. @@ -332,7 +330,7 @@ def deployFrameworks(frameworks, bundlePath, binaryPath, strip, verbose, deploym # Get the Qt path from one of the Qt frameworks if deploymentInfo.qtPath is None and framework.isQtFramework(): deploymentInfo.detectQtPath(framework.frameworkDirectory) - + if framework.installName.startswith("@executable_path") or framework.installName.startswith(bundlePath): if verbose >= 2: print(framework.frameworkName, "already deployed, skipping.") @@ -543,7 +541,7 @@ if len(config.fancy) == 1: if verbose >= 1: sys.stderr.write("Error: Could not import plistlib which is required for fancy disk images.\n") sys.exit(1) - + p = config.fancy[0] if verbose >= 3: print("Fancy: Loading \"%s\"..." % p) @@ -717,22 +715,6 @@ elif config.sign: if config.dmg is not None: - #Patch in check_output for Python 2.6 - if "check_output" not in dir( subprocess ): - def f(*popenargs, **kwargs): - if 'stdout' in kwargs: - raise ValueError('stdout argument not allowed, it will be overridden.') - process = subprocess.Popen(stdout=subprocess.PIPE, *popenargs, **kwargs) - output, unused_err = process.communicate() - retcode = process.poll() - if retcode: - cmd = kwargs.get("args") - if cmd is None: - cmd = popenargs[0] - raise CalledProcessError(retcode, cmd) - return output - subprocess.check_output = f - def runHDIUtil(verb, image_basename, **kwargs): hdiutil_args = ["hdiutil", verb, image_basename + ".dmg"] if "capture_stdout" in kwargs: @@ -750,7 +732,7 @@ if config.dmg is not None: if not value is True: hdiutil_args.append(str(value)) - return run(hdiutil_args) + return run(hdiutil_args, universal_newlines=True) if verbose >= 2: if fancy is None: @@ -792,7 +774,7 @@ if config.dmg is not None: except subprocess.CalledProcessError as e: sys.exit(e.returncode) - m = re.search("/Volumes/(.+$)", output.decode()) + m = re.search("/Volumes/(.+$)", output) disk_root = m.group(0) disk_name = m.group(1) @@ -876,7 +858,7 @@ if config.dmg is not None: if verbose >= 2: print("+ Finalizing .dmg disk image +") time.sleep(5) - + try: runHDIUtil("convert", dmg_name + ".temp", format="UDBZ", o=dmg_name + ".dmg", ov=True) except subprocess.CalledProcessError as e: diff --git a/contrib/testgen/base58.py b/contrib/testgen/base58.py index 56edf292c106..a11d63e2bcb8 100644 --- a/contrib/testgen/base58.py +++ b/contrib/testgen/base58.py @@ -28,7 +28,9 @@ def b58encode(v): """ long_value = 0 for (i, c) in enumerate(v[::-1]): - long_value += (256**i) * ord(c) + if isinstance(c, str): + c = ord(c) + long_value += (256**i) * c result = '' while long_value >= __b58base: @@ -41,7 +43,7 @@ def b58encode(v): # leading 0-bytes in the input become leading-1s nPad = 0 for c in v: - if c == '\0': nPad += 1 + if c == 0: nPad += 1 else: break return (__b58chars[0]*nPad) + result @@ -50,8 +52,10 @@ def b58decode(v, length = None): """ decode v into a string of len bytes """ long_value = 0 - for (i, c) in enumerate(v[::-1]): - long_value += __b58chars.find(c) * (__b58base**i) + for i, c in enumerate(v[::-1]): + pos = __b58chars.find(c) + assert pos != -1 + long_value += pos * (__b58base**i) result = bytes() while long_value >= 256: @@ -62,10 +66,12 @@ def b58decode(v, length = None): nPad = 0 for c in v: - if c == __b58chars[0]: nPad += 1 - else: break + if c == __b58chars[0]: + nPad += 1 + continue + break - result = chr(0)*nPad + result + result = bytes(nPad) + result if length is not None and len(result) != length: return None diff --git a/contrib/testgen/gen_base58_test_vectors.py b/contrib/testgen/gen_base58_test_vectors.py index a0b4b7d20105..ccdcfa5269c1 100755 --- a/contrib/testgen/gen_base58_test_vectors.py +++ b/contrib/testgen/gen_base58_test_vectors.py @@ -1,11 +1,11 @@ -#!/usr/bin/env python +#!/usr/bin/env python3 # Copyright (c) 2012 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. ''' Generate valid and invalid base58 address and private key test vectors. -Usage: +Usage: gen_base58_test_vectors.py valid 50 > ../../src/test/data/base58_keys_valid.json gen_base58_test_vectors.py invalid 50 > ../../src/test/data/base58_keys_invalid.json ''' @@ -46,8 +46,8 @@ def is_valid(v): if result is None: return False for template in templates: - prefix = str(bytearray(template[0])) - suffix = str(bytearray(template[2])) + prefix = bytearray(template[0]) + suffix = bytearray(template[2]) if result.startswith(prefix) and result.endswith(suffix): if (len(result) - len(prefix) - len(suffix)) == template[1]: return True @@ -57,20 +57,23 @@ def gen_valid_vectors(): '''Generate valid test vectors''' while True: for template in templates: - prefix = str(bytearray(template[0])) - payload = os.urandom(template[1]) - suffix = str(bytearray(template[2])) + prefix = bytearray(template[0]) + payload = bytearray(os.urandom(template[1])) + suffix = bytearray(template[2]) rv = b58encode_chk(prefix + payload + suffix) assert is_valid(rv) - metadata = dict([(x,y) for (x,y) in zip(metadata_keys,template[3]) if y is not None]) - yield (rv, b2a_hex(payload), metadata) + metadata = {x: y for x, y in zip(metadata_keys,template[3]) if y is not None} + hexrepr = b2a_hex(payload) + if isinstance(hexrepr, bytes): + hexrepr = hexrepr.decode('utf8') + yield (rv, hexrepr, metadata) def gen_invalid_vector(template, corrupt_prefix, randomize_payload_size, corrupt_suffix): '''Generate possibly invalid vector''' if corrupt_prefix: prefix = os.urandom(1) else: - prefix = str(bytearray(template[0])) + prefix = bytearray(template[0]) if randomize_payload_size: payload = os.urandom(max(int(random.expovariate(0.5)), 50)) @@ -80,7 +83,7 @@ def gen_invalid_vector(template, corrupt_prefix, randomize_payload_size, corrupt if corrupt_suffix: suffix = os.urandom(len(template[2])) else: - suffix = str(bytearray(template[2])) + suffix = bytearray(template[2]) return b58encode_chk(prefix + payload + suffix) diff --git a/share/qt/extract_strings_qt.py b/share/qt/extract_strings_qt.py index 9106af45613c..80b38fb4e355 100755 --- a/share/qt/extract_strings_qt.py +++ b/share/qt/extract_strings_qt.py @@ -1,4 +1,4 @@ -#!/usr/bin/env python +#!/usr/bin/env python3 # Copyright (c) 2012-2016 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. @@ -6,7 +6,6 @@ Extract _("...") strings for translation and convert to Qt stringdefs so that they can be picked up by Qt linguist. ''' -from __future__ import division,print_function,unicode_literals from subprocess import Popen, PIPE import operator import os diff --git a/share/rpcuser/rpcuser.py b/share/rpcuser/rpcuser.py index f806a810e08c..ab3d8c4ed3de 100755 --- a/share/rpcuser/rpcuser.py +++ b/share/rpcuser/rpcuser.py @@ -1,4 +1,4 @@ -#!/usr/bin/env python2 +#!/usr/bin/env python3 # 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. From b1e5fac728c1fb7e55737d13ebc9cc514d4775da Mon Sep 17 00:00:00 2001 From: Alexander Block Date: Mon, 13 Aug 2018 22:21:42 +0200 Subject: [PATCH 041/282] Backport move to Ubuntu Bionic and GCC7 in Gitian builds * Add stdin, stdout, stderr to ignored export list * Merge bitcoin#13171: Change gitian-descriptors to use bionic instead c1afe32 Change gitian-descriptors to use bionic instead (Chun Kuan Lee) Pull request description: I have tested this with Ubuntu Bionic host with lxc 3.0.0, the gitian-build for Windows and MacOSX work fine, but there is an issue about it for Linux. Failed at check-symbol: ``` test/test_bitcoin: symbol __divmoddi4 from unsupported version GCC_7.0.0 test/test_bitcoin: symbol log2f from unsupported version GLIBC_2.27 qt/bitcoin-qt: symbol __divmoddi4 from unsupported version GCC_7.0.0 qt/bitcoin-qt: symbol log2f from unsupported version GLIBC_2.27 ``` I think this should be fixed in `./configure --enable-glibc-back-compat` Should not be merged before bitcoin#13177 devrandom/gitian-builder#178 Close bitcoin#12511 Tree-SHA512: 257d75d5b6864e105279f7a7b992fbbd7903cdbe3300b66dacec0a783d267707d9dbbfe0e64a36983ca1eca50a2a5e1cdb222b6d3745ccc3e5fc5636c88b581f * Use IN6ADDR_ANY_INIT instead of in6addr_any This is the same fix as bitcoin@fc6a9f2 Couldn't backport the original commit as we are missing some refactorings. --- contrib/devtools/symbol-check.py | 2 +- contrib/gitian-build.sh | 9 ++++----- contrib/gitian-descriptors/gitian-linux.yml | 16 ++++++++-------- contrib/gitian-descriptors/gitian-osx-signer.yml | 2 +- contrib/gitian-descriptors/gitian-osx.yml | 4 ++-- contrib/gitian-descriptors/gitian-win-signer.yml | 2 +- contrib/gitian-descriptors/gitian-win.yml | 9 +++++---- src/init.cpp | 2 +- 8 files changed, 23 insertions(+), 23 deletions(-) diff --git a/contrib/devtools/symbol-check.py b/contrib/devtools/symbol-check.py index c23ee5624c00..c945fcbde94d 100755 --- a/contrib/devtools/symbol-check.py +++ b/contrib/devtools/symbol-check.py @@ -46,7 +46,7 @@ # Ignore symbols that are exported as part of every executable IGNORE_EXPORTS = { -'_edata', '_end', '_init', '__bss_start', '_fini', '_IO_stdin_used' +'_edata', '_end', '_init', '__bss_start', '_fini', '_IO_stdin_used', 'stdin', 'stdout', 'stderr' } READELF_CMD = os.getenv('READELF', '/usr/bin/readelf') CPPFILT_CMD = os.getenv('CPPFILT', '/usr/bin/c++filt') diff --git a/contrib/gitian-build.sh b/contrib/gitian-build.sh index d05bcf69295a..e773114b00c7 100644 --- a/contrib/gitian-build.sh +++ b/contrib/gitian-build.sh @@ -258,14 +258,13 @@ then if [[ -n "$USE_LXC" ]] then sudo apt-get install lxc - bin/make-base-vm --suite trusty --arch amd64 --lxc - + bin/make-base-vm --suite bionic --arch amd64 --lxc elif [[ -n "$USE_DOCKER" ]] then sudo apt-get install docker-ce - bin/make-base-vm --suite trusty --arch amd64 --docker + bin/make-base-vm --suite bionic --arch amd64 --docker else - bin/make-base-vm --suite trusty --arch amd64 + bin/make-base-vm --suite bionic --arch amd64 fi popd fi @@ -377,7 +376,7 @@ fi if [[ $sign = true ]] then - + pushd ./gitian-builder # Sign Windows if [[ $windows = true ]] diff --git a/contrib/gitian-descriptors/gitian-linux.yml b/contrib/gitian-descriptors/gitian-linux.yml index e4345db8e593..c77bec48561a 100755 --- a/contrib/gitian-descriptors/gitian-linux.yml +++ b/contrib/gitian-descriptors/gitian-linux.yml @@ -2,23 +2,23 @@ name: "absolute-linux-0.12" enable_cache: true suites: -- "trusty" +- "bionic" architectures: - "amd64" packages: - "curl" - "g++-aarch64-linux-gnu" -- "g++-4.8-aarch64-linux-gnu" -- "gcc-4.8-aarch64-linux-gnu" +- "g++-7-aarch64-linux-gnu" +- "gcc-7-aarch64-linux-gnu" - "binutils-aarch64-linux-gnu" - "g++-arm-linux-gnueabihf" -- "g++-4.8-arm-linux-gnueabihf" -- "gcc-4.8-arm-linux-gnueabihf" +- "g++-7-arm-linux-gnueabihf" +- "gcc-7-arm-linux-gnueabihf" - "binutils-arm-linux-gnueabihf" -- "g++-4.8-multilib" -- "gcc-4.8-multilib" +- "g++-7-multilib" +- "gcc-7-multilib" - "binutils-gold" -- "git-core" +- "git" - "pkg-config" - "autoconf" - "libtool" diff --git a/contrib/gitian-descriptors/gitian-osx-signer.yml b/contrib/gitian-descriptors/gitian-osx-signer.yml index a3ce72233564..e49482bb3a11 100644 --- a/contrib/gitian-descriptors/gitian-osx-signer.yml +++ b/contrib/gitian-descriptors/gitian-osx-signer.yml @@ -1,7 +1,7 @@ --- name: "absolute-dmg-signer" suites: -- "trusty" +- "bionic" architectures: - "amd64" packages: diff --git a/contrib/gitian-descriptors/gitian-osx.yml b/contrib/gitian-descriptors/gitian-osx.yml index 1ae179fd4ec3..632aa826c582 100644 --- a/contrib/gitian-descriptors/gitian-osx.yml +++ b/contrib/gitian-descriptors/gitian-osx.yml @@ -2,14 +2,14 @@ name: "absolute-osx-0.12" enable_cache: true suites: -- "trusty" +- "bionic" architectures: - "amd64" packages: - "ca-certificates" - "curl" - "g++" -- "git-core" +- "git" - "pkg-config" - "autoconf" - "librsvg2-bin" diff --git a/contrib/gitian-descriptors/gitian-win-signer.yml b/contrib/gitian-descriptors/gitian-win-signer.yml index 81712a5cf123..b8414ef2bb35 100644 --- a/contrib/gitian-descriptors/gitian-win-signer.yml +++ b/contrib/gitian-descriptors/gitian-win-signer.yml @@ -1,7 +1,7 @@ --- name: "absolute-win-signer" suites: -- "trusty" +- "bionic" architectures: - "amd64" packages: diff --git a/contrib/gitian-descriptors/gitian-win.yml b/contrib/gitian-descriptors/gitian-win.yml index 7ff889015521..f3296971ca99 100755 --- a/contrib/gitian-descriptors/gitian-win.yml +++ b/contrib/gitian-descriptors/gitian-win.yml @@ -2,13 +2,13 @@ name: "absolute-win-0.12" enable_cache: true suites: -- "trusty" +- "bionic" architectures: - "amd64" packages: - "curl" - "g++" -- "git-core" +- "git" - "pkg-config" - "autoconf" - "libtool" @@ -22,6 +22,7 @@ packages: - "ca-certificates" - "python" - "python3" +- "rename" remotes: - "url": "https://github.com/absolute-community/absolute.git" "dir": "absolute" @@ -30,7 +31,7 @@ script: | WRAP_DIR=$HOME/wrapped HOSTS="i686-w64-mingw32 x86_64-w64-mingw32" CONFIGFLAGS="--enable-reduce-exports --disable-bench --disable-gui-tests" - FAKETIME_HOST_PROGS="g++ ar ranlib nm windres strip objcopy" + FAKETIME_HOST_PROGS="ar ranlib nm windres strip objcopy" FAKETIME_PROGS="date makensis zip" HOST_CFLAGS="-O2 -g" HOST_CXXFLAGS="-O2 -g" @@ -109,7 +110,7 @@ script: | for prog in gcc g++; do echo '#!/bin/bash' > ${WRAP_DIR}/${i}-${prog} echo "# GCCVERSION=${GCCVERSION}" >> ${WRAP_DIR}/${i}-${prog} - echo "REAL=\`which -a ${i}-${prog} | grep -v ${WRAP_DIR}/${i}-${prog} | head -1\`" >> ${WRAP_DIR}/${i}-${prog} + echo "REAL=\`which -a ${i}-${prog}-posix | grep -v ${WRAP_DIR}/${i}-${prog} | head -1\`" >> ${WRAP_DIR}/${i}-${prog} echo '# Add the gcc version to the wrapper so that ccache takes this into account (we use CCACHE_COMPILERCHECK=content)' >> ${WRAP_DIR}/${i}-${prog} echo "# `${prog} --version | head -1`" >> ${WRAP_DIR}/${i}-${prog} echo 'export LD_PRELOAD=/usr/lib/x86_64-linux-gnu/faketime/libfaketime.so.1' >> ${WRAP_DIR}/${i}-${prog} diff --git a/src/init.cpp b/src/init.cpp index e9571e093497..6177b9e7a4d9 100644 --- a/src/init.cpp +++ b/src/init.cpp @@ -1512,7 +1512,7 @@ bool AppInitMain(boost::thread_group& threadGroup, CScheduler& scheduler) if (!mapMultiArgs.count("-bind") && !mapMultiArgs.count("-whitebind")) { struct in_addr inaddr_any; inaddr_any.s_addr = INADDR_ANY; - fBound |= Bind(connman, CService(in6addr_any, GetListenPort()), BF_NONE); + fBound |= Bind(connman, CService((in6_addr)IN6ADDR_ANY_INIT, GetListenPort()), BF_NONE); fBound |= Bind(connman, CService(inaddr_any, GetListenPort()), !fBound ? BF_REPORT_ERROR : BF_NONE); } if (!fBound) From 014293c45a055a61cbd56da7982f6680a37b841b Mon Sep 17 00:00:00 2001 From: Alexander Block Date: Tue, 14 Aug 2018 11:58:38 +0200 Subject: [PATCH 042/282] Prepare for AIP3 operator reward payments and switch to array * Prepare for AIP3 operator reward payments and switch to array in getblocktemplate This commit allows to later split MN rewards into multiple recipients, e.g. the owner reward and operator reward. It also updates the getblocktemplate output to return an array of MN payments instead of a single entry. This should allow MN miners and pool operators to prepare themself for the upcoming changes in regard to operator rewards. * txoutsMasternode -> voutMasternode * More renaming * Consider all masternode payments when looking for a known masternode --- src/masternode-payments.cpp | 108 ++++++++++++++++++++++++------------ src/masternode-payments.h | 6 +- src/miner.cpp | 4 +- src/miner.h | 4 +- src/rpc/mining.cpp | 37 +++++++----- src/validation.cpp | 13 ++++- 6 files changed, 113 insertions(+), 59 deletions(-) diff --git a/src/masternode-payments.cpp b/src/masternode-payments.cpp index 9b123f6e9cd9..e353b155db91 100644 --- a/src/masternode-payments.cpp +++ b/src/masternode-payments.cpp @@ -206,14 +206,14 @@ bool IsBlockPayeeValid(const CTransaction& txNew, int nBlockHeight, CAmount bloc return true; } -void FillBlockPayments(CMutableTransaction& txNew, int nBlockHeight, CAmount blockReward, CTxOut& txoutMasternodeRet, std::vector& voutSuperblockRet) +void FillBlockPayments(CMutableTransaction& txNew, int nBlockHeight, CAmount blockReward, std::vector& voutMasternodePaymentsRet, std::vector& voutSuperblockPaymentsRet) { // only create superblocks if spork is enabled AND if superblock is actually triggered // (height should be validated inside) if(sporkManager.IsSporkActive(SPORK_9_SUPERBLOCKS_ENABLED) && CSuperblockManager::IsSuperblockTriggered(nBlockHeight)) { LogPrint("gobject", "%s -- triggered superblock creation at height %d\n", __func__, nBlockHeight); - CSuperblockManager::GetSuperblockPayments(nBlockHeight, voutSuperblockRet); + CSuperblockManager::GetSuperblockPayments(nBlockHeight, voutSuperblockPaymentsRet); } // TODO this is a placeholder until DIP3 is merged, which will allow superblock payments and MN reward payments @@ -222,24 +222,30 @@ void FillBlockPayments(CMutableTransaction& txNew, int nBlockHeight, CAmount blo bool allowSuperblockAndMNReward = false; // don't allow payments to superblocks AND masternodes before spork15 activation - if (!voutSuperblockRet.empty() && !allowSuperblockAndMNReward) { - txNew.vout.insert(txNew.vout.end(), voutSuperblockRet.begin(), voutSuperblockRet.end()); + if (!voutSuperblockPaymentsRet.empty() && !allowSuperblockAndMNReward) { + txNew.vout.insert(txNew.vout.end(), voutSuperblockPaymentsRet.begin(), voutSuperblockPaymentsRet.end()); return; } - if (!mnpayments.GetMasternodeTxOut(nBlockHeight, blockReward, txoutMasternodeRet)) { + if (!mnpayments.GetMasternodeTxOuts(nBlockHeight, blockReward, voutMasternodePaymentsRet)) { // no idea whom to pay (MN list empty?), lets hope for the best return; } - txNew.vout.emplace_back(txoutMasternodeRet); - txNew.vout.insert(txNew.vout.end(), voutSuperblockRet.begin(), voutSuperblockRet.end()); + txNew.vout.insert(txNew.vout.end(), voutMasternodePaymentsRet.begin(), voutMasternodePaymentsRet.end()); + txNew.vout.insert(txNew.vout.end(), voutSuperblockPaymentsRet.begin(), voutSuperblockPaymentsRet.end()); - // subtract MN payment from miner reward - txNew.vout[0].nValue -= txoutMasternodeRet.nValue; + std::string voutMasternodeStr; + for (const auto& txout : voutMasternodePaymentsRet) { + // subtract MN payment from miner reward + txNew.vout[0].nValue -= txout.nValue; + if (!voutMasternodeStr.empty()) + voutMasternodeStr += ","; + voutMasternodeStr += txout.ToString(); + } - LogPrint("mnpayments", "%s -- nBlockHeight %d blockReward %lld txoutMasternodeRet %s txNew %s", __func__, - nBlockHeight, blockReward, txoutMasternodeRet.ToString(), txNew.ToString()); + LogPrint("mnpayments", "%s -- nBlockHeight %d blockReward %lld voutMasternodePaymentsRet \"%s\" txNew %s", __func__, + nBlockHeight, blockReward, voutMasternodeStr, txNew.ToString()); } std::string GetRequiredPaymentsString(int nBlockHeight) @@ -278,19 +284,17 @@ bool CMasternodePayments::UpdateLastVote(const CMasternodePaymentVote& vote) } /** -* FillBlockPayee +* GetMasternodeTxOuts * -* Get masternode payment tx output +* Get masternode payment tx outputs */ -bool CMasternodePayments::GetMasternodeTxOut(int nBlockHeight, CAmount blockReward, CTxOut& txoutMasternodeRet) const +bool CMasternodePayments::GetMasternodeTxOuts(int nBlockHeight, CAmount blockReward, std::vector& voutMasternodePaymentsRet) const { // make sure it's not filled yet - txoutMasternodeRet = CTxOut(); - - CScript payee; + voutMasternodePaymentsRet.clear(); - if(!GetBlockPayee(nBlockHeight, payee)) { + if(!GetBlockTxOuts(nBlockHeight, blockReward, voutMasternodePaymentsRet)) { // no masternode detected... int nCount = 0; masternode_info_t mnInfo; @@ -300,18 +304,18 @@ bool CMasternodePayments::GetMasternodeTxOut(int nBlockHeight, CAmount blockRewa return false; } // fill payee with locally calculated winner and hope for the best - payee = GetScriptForDestination(mnInfo.keyIDCollateralAddress); + CScript payee = GetScriptForDestination(mnInfo.keyIDCollateralAddress); + CAmount masternodePayment = GetMasternodePayment(nBlockHeight, blockReward); + voutMasternodePaymentsRet.emplace_back(masternodePayment, payee); } - // GET MASTERNODE PAYMENT VARIABLES SETUP - CAmount masternodePayment = GetMasternodePayment(nBlockHeight, blockReward); - txoutMasternodeRet = CTxOut(masternodePayment, payee); - - CTxDestination address1; - ExtractDestination(payee, address1); - CBitcoinAddress address2(address1); + for (const auto& txout : voutMasternodePaymentsRet) { + CTxDestination address1; + ExtractDestination(txout.scriptPubKey, address1); + CBitcoinAddress address2(address1); - LogPrintf("CMasternodePayments::%s -- Masternode payment %lld to %s\n", __func__, masternodePayment, address2.ToString()); + LogPrintf("CMasternodePayments::%s -- Masternode payment %lld to %s\n", __func__, txout.nValue, address2.ToString()); + } return true; } @@ -505,12 +509,20 @@ bool CMasternodePaymentVote::Sign() return true; } -bool CMasternodePayments::GetBlockPayee(int nBlockHeight, CScript& payeeRet) const +bool CMasternodePayments::GetBlockTxOuts(int nBlockHeight, CAmount blockReward, std::vector& voutMasternodePaymentsRet) const { - LOCK(cs_mapMasternodeBlocks); + voutMasternodePaymentsRet.clear(); + + CAmount masternodeReward = GetMasternodePayment(nBlockHeight, blockReward); + LOCK(cs_mapMasternodeBlocks); auto it = mapMasternodeBlocks.find(nBlockHeight); - return it != mapMasternodeBlocks.end() && it->second.GetBestPayee(payeeRet); + CScript payee; + if (it == mapMasternodeBlocks.end() || !it->second.GetBestPayee(payee)) { + return false; + } + voutMasternodePaymentsRet.emplace_back(masternodeReward, payee); + return true; } // Is this masternode scheduled to get paid soon? @@ -524,11 +536,14 @@ bool CMasternodePayments::IsScheduled(const masternode_info_t& mnInfo, int nNotB CScript mnpayee; mnpayee = GetScriptForDestination(mnInfo.keyIDCollateralAddress); - CScript payee; for(int64_t h = nCachedBlockHeight; h <= nCachedBlockHeight + 8; h++){ if(h == nNotBlockHeight) continue; - if(GetBlockPayee(h, payee) && mnpayee == payee) { - return true; + std::vector voutMasternodePayments; + if(GetBlockTxOuts(h, 0, voutMasternodePayments)) { + for (const auto& txout : voutMasternodePayments) { + if (txout.scriptPubKey == mnpayee) + return true; + } } } @@ -692,9 +707,30 @@ std::string CMasternodePayments::GetRequiredPaymentsString(int nBlockHeight) con bool CMasternodePayments::IsTransactionValid(const CTransaction& txNew, int nBlockHeight, CAmount blockReward) const { - LOCK(cs_mapMasternodeBlocks); - const auto it = mapMasternodeBlocks.find(nBlockHeight); - return it == mapMasternodeBlocks.end() ? true : it->second.IsTransactionValid(txNew); + std::vector voutMasternodePayments; + if (!GetBlockTxOuts(nBlockHeight, blockReward, voutMasternodePayments)) { + LogPrintf("CMasternodePayments::%s -- ERROR failed to get payees for block at height %s\n", __func__, nBlockHeight); + return false; + } + + for (const auto& txout : voutMasternodePayments) { + bool found = false; + for (const auto& txout2 : txNew.vout) { + if (txout == txout2) { + found = true; + break; + } + } + if (!found) { + CTxDestination dest; + if (!ExtractDestination(txout.scriptPubKey, dest)) + assert(false); + LogPrintf("CMasternodePayments::%s -- ERROR failed to find expected payee %s in block at height %s\n", __func__, CBitcoinAddress(dest).ToString(), nBlockHeight); + return false; + } + } + + return true; } void CMasternodePayments::CheckAndRemove() diff --git a/src/masternode-payments.h b/src/masternode-payments.h index 1d6141fe8314..3079bd52f478 100644 --- a/src/masternode-payments.h +++ b/src/masternode-payments.h @@ -36,7 +36,7 @@ extern CMasternodePayments mnpayments; /// TODO: all 4 functions do not belong here really, they should be refactored/moved somewhere (main.cpp ?) bool IsBlockValueValid(const CBlock& block, int nBlockHeight, CAmount blockReward, std::string& strErrorRet); bool IsBlockPayeeValid(const CTransaction& txNew, int nBlockHeight, CAmount blockReward); -void FillBlockPayments(CMutableTransaction& txNew, int nBlockHeight, CAmount blockReward, CTxOut& txoutMasternodeRet, std::vector& voutSuperblockRet); +void FillBlockPayments(CMutableTransaction& txNew, int nBlockHeight, CAmount blockReward, std::vector& voutMasternodePaymentsRet, std::vector& voutSuperblockPaymentsRet); std::string GetRequiredPaymentsString(int nBlockHeight); class CMasternodePayee @@ -214,7 +214,7 @@ class CMasternodePayments void RequestLowDataPaymentBlocks(CNode* pnode, CConnman& connman) const; void CheckAndRemove(); - bool GetBlockPayee(int nBlockHeight, CScript& payeeRet) const; + bool GetBlockTxOuts(int nBlockHeight, CAmount blockReward, std::vector& voutMasternodePaymentsRet) const; bool IsTransactionValid(const CTransaction& txNew, int nBlockHeight, CAmount blockReward) const; bool IsScheduled(const masternode_info_t& mnInfo, int nNotBlockHeight) const; @@ -223,7 +223,7 @@ class CMasternodePayments int GetMinMasternodePaymentsProto() const; void ProcessMessage(CNode* pfrom, const std::string& strCommand, CDataStream& vRecv, CConnman& connman); std::string GetRequiredPaymentsString(int nBlockHeight) const; - bool GetMasternodeTxOut(int nBlockHeight, CAmount blockReward, CTxOut& txoutMasternodeRet) const; + bool GetMasternodeTxOuts(int nBlockHeight, CAmount blockReward, std::vector& voutMasternodePaymentsRet) const; std::string ToString() const; int GetBlockCount() const { return mapMasternodeBlocks.size(); } diff --git a/src/miner.cpp b/src/miner.cpp index 29e539f9f78d..f5eff8e299a4 100644 --- a/src/miner.cpp +++ b/src/miner.cpp @@ -172,9 +172,9 @@ std::unique_ptr BlockAssembler::CreateNewBlock(const CScript& sc // Update coinbase transaction with additional info about masternode and governance payments, // get some info back to pass to getblocktemplate - FillBlockPayments(coinbaseTx, nHeight, blockReward, pblocktemplate->txoutMasternode, pblocktemplate->voutSuperblock); + FillBlockPayments(coinbaseTx, nHeight, blockReward, pblocktemplate->voutMasternodePayments, pblocktemplate->voutSuperblockPayments); // LogPrintf("CreateNewBlock -- nBlockHeight %d blockReward %lld txoutMasternode %s coinbaseTx %s", - // nHeight, blockReward, pblocktemplate->txoutMasternode.ToString(), coinbaseTx.ToString()); + // nHeight, blockReward, pblocktemplate->txoutsMasternode.ToString(), coinbaseTx.ToString()); pblock->vtx[0] = MakeTransactionRef(std::move(coinbaseTx)); pblocktemplate->vTxFees[0] = -nFees; diff --git a/src/miner.h b/src/miner.h index ab2a5f2fc3a9..c73bc626ca63 100644 --- a/src/miner.h +++ b/src/miner.h @@ -31,8 +31,8 @@ struct CBlockTemplate std::vector vTxFees; std::vector vTxSigOps; uint32_t nPrevBits; // nBits of previous block (for subsidy calculation) - CTxOut txoutMasternode; // masternode payment - std::vector voutSuperblock; // superblock payment + std::vector voutMasternodePayments; // masternode payment + std::vector voutSuperblockPayments; // superblock payment }; // Container for tracking updates to ancestor feerate as we include (parent) diff --git a/src/rpc/mining.cpp b/src/rpc/mining.cpp index 6b819f0716db..3f0824ce8514 100644 --- a/src/rpc/mining.cpp +++ b/src/rpc/mining.cpp @@ -390,10 +390,12 @@ UniValue getblocktemplate(const JSONRPCRequest& request) " \"bits\" : \"xxxxxxxx\", (string) compressed target of next block\n" " \"previousbits\" : \"xxxxxxxx\", (string) compressed target of current highest block\n" " \"height\" : n (numeric) The height of the next block\n" - " \"masternode\" : { (json object) required masternode payee that must be included in the next block\n" - " \"payee\" : \"xxxx\", (string) payee address\n" - " \"script\" : \"xxxx\", (string) payee scriptPubKey\n" - " \"amount\": n (numeric) required amount to pay\n" + " \"masternode\" : [ (array) required masternode payments that must be included in the next block\n" + " {\n" + " \"payee\" : \"xxxx\", (string) payee address\n" + " \"script\" : \"xxxx\", (string) payee scriptPubKey\n" + " \"amount\": n (numeric) required amount to pay\n" + " }\n" " },\n" " \"masternode_payments_started\" : true|false, (boolean) true, if masternode payments started\n" " \"masternode_payments_enforced\" : true|false, (boolean) true, if masternode payments are enforced\n" @@ -494,11 +496,16 @@ UniValue getblocktemplate(const JSONRPCRequest& request) } // when enforcement is on we need information about a masternode payee or otherwise our block is going to be orphaned by the network - CScript payee; + std::vector voutMasternodePayments; if (sporkManager.IsSporkActive(SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT) && !masternodeSync.IsWinnersListSynced() +<<<<<<< HEAD && !mnpayments.GetBlockPayee(chainActive.Height() + 1, payee)) throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "Absolute Core is downloading masternode winners..."); +======= + && !mnpayments.GetBlockTxOuts(chainActive.Height() + 1, 0, voutMasternodePayments)) + throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "Dash Core is downloading masternode winners..."); +>>>>>>> 50eb98d90... Prepare for DIP3 operator reward payments and switch to array in getblocktemplate (#2216) // next bock is a superblock and we need governance info to correctly construct it if (sporkManager.IsSporkActive(SPORK_9_SUPERBLOCKS_ENABLED) @@ -703,22 +710,26 @@ UniValue getblocktemplate(const JSONRPCRequest& request) result.push_back(Pair("previousbits", strprintf("%08x", pblocktemplate->nPrevBits))); result.push_back(Pair("height", (int64_t)(pindexPrev->nHeight+1))); - UniValue masternodeObj(UniValue::VOBJ); - if(pblocktemplate->txoutMasternode != CTxOut()) { + UniValue masternodeObj(UniValue::VARR); + for (const auto& txout : pblocktemplate->voutMasternodePayments) { CTxDestination address1; - ExtractDestination(pblocktemplate->txoutMasternode.scriptPubKey, address1); + ExtractDestination(txout.scriptPubKey, address1); CBitcoinAddress address2(address1); - masternodeObj.push_back(Pair("payee", address2.ToString().c_str())); - masternodeObj.push_back(Pair("script", HexStr(pblocktemplate->txoutMasternode.scriptPubKey))); - masternodeObj.push_back(Pair("amount", pblocktemplate->txoutMasternode.nValue)); + + UniValue obj(UniValue::VOBJ); + obj.push_back(Pair("payee", address2.ToString().c_str())); + obj.push_back(Pair("script", HexStr(txout.scriptPubKey))); + obj.push_back(Pair("amount", txout.nValue)); + masternodeObj.push_back(obj); } + result.push_back(Pair("masternode", masternodeObj)); result.push_back(Pair("masternode_payments_started", pindexPrev->nHeight + 1 > consensusParams.nMasternodePaymentsStartBlock)); result.push_back(Pair("masternode_payments_enforced", sporkManager.IsSporkActive(SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT))); UniValue superblockObjArray(UniValue::VARR); - if(pblocktemplate->voutSuperblock.size()) { - for (const auto& txout : pblocktemplate->voutSuperblock) { + if(pblocktemplate->voutSuperblockPayments.size()) { + for (const auto& txout : pblocktemplate->voutSuperblockPayments) { UniValue entry(UniValue::VOBJ); CTxDestination address1; ExtractDestination(txout.scriptPubKey, address1); diff --git a/src/validation.cpp b/src/validation.cpp index 5c2ee07654c3..2498eade8fa8 100644 --- a/src/validation.cpp +++ b/src/validation.cpp @@ -1959,13 +1959,20 @@ int32_t ComputeBlockVersion(const CBlockIndex* pindexPrev, const Consensus::Para ThresholdState state = VersionBitsState(pindexPrev, params, pos, versionbitscache); const struct BIP9DeploymentInfo& vbinfo = VersionBitsDeploymentInfo[pos]; if (vbinfo.check_mn_protocol && state == THRESHOLD_STARTED && !fAssumeMasternodeIsUpgraded) { - CScript payee; + std::vector voutMasternodePayments; masternode_info_t mnInfo; - if (!mnpayments.GetBlockPayee(pindexPrev->nHeight + 1, payee)) { + if (!mnpayments.GetBlockTxOuts(pindexPrev->nHeight + 1, 0, voutMasternodePayments)) { // no votes for this block continue; } - if (!mnodeman.GetMasternodeInfo(payee, mnInfo)) { + bool mnKnown = false; + for (const auto& txout : voutMasternodePayments) { + if (mnodeman.GetMasternodeInfo(txout.scriptPubKey, mnInfo)) { + mnKnown = true; + break; + } + } + if (!mnKnown) { // unknown masternode continue; } From 9c9e65dd5c04ed356becb301a95f4c3d47a953b5 Mon Sep 17 00:00:00 2001 From: Alexander Block Date: Tue, 14 Aug 2018 21:36:15 +0200 Subject: [PATCH 043/282] Build bionic base image in Jenkinsfile.gitian & update docs * Build bionic base image in Jenkinsfile.gitian We updated gitian builds to use bionic, so we should also update the Jenkinsfile * Update docs --- Jenkinsfile.gitian | 2 +- contrib/gitian-descriptors/README.md | 2 +- doc/gitian-building.md | 14 +++++++------- 3 files changed, 9 insertions(+), 9 deletions(-) diff --git a/Jenkinsfile.gitian b/Jenkinsfile.gitian index 87fb1e849e39..8756e5311ad9 100644 --- a/Jenkinsfile.gitian +++ b/Jenkinsfile.gitian @@ -88,7 +88,7 @@ for(int i = 0; i < targets.size(); i++) { } stage("${target}/base-vm") { dir('gitian-builder') { - sh "./bin/make-base-vm --suite trusty --arch amd64 --docker" + sh "./bin/make-base-vm --suite bionic --arch amd64 --docker" } } diff --git a/contrib/gitian-descriptors/README.md b/contrib/gitian-descriptors/README.md index 4f53e113dbcf..a7cf46a02ed4 100644 --- a/contrib/gitian-descriptors/README.md +++ b/contrib/gitian-descriptors/README.md @@ -26,7 +26,7 @@ Once you've got the right hardware and software: # Create base images cd gitian-builder - bin/make-base-vm --suite trusty --arch amd64 + bin/make-base-vm --suite bionic --arch amd64 cd .. # Get inputs (see doc/release-process.md for exact inputs needed and where to get them) diff --git a/doc/gitian-building.md b/doc/gitian-building.md index c5b847a880f8..5615385cdc5d 100644 --- a/doc/gitian-building.md +++ b/doc/gitian-building.md @@ -324,7 +324,7 @@ Execute the following as user `debian`: ```bash cd gitian-builder -bin/make-base-vm --lxc --arch amd64 --suite trusty +bin/make-base-vm --lxc --arch amd64 --suite bionic ``` There will be a lot of warnings printed during the build of the image. These can be ignored. @@ -375,7 +375,7 @@ Output from `gbuild` will look something like Resolving deltas: 100% (41590/41590), done. From https://github.com/absolute-community/absolute ... (new tags, new branch etc) - --- Building for trusty amd64 --- + --- Building for bionic amd64 --- Stopping target if it is up Making a new image copy stdin: is not a tty @@ -424,14 +424,14 @@ So, if you use LXC: export PATH="$PATH":/path/to/gitian-builder/libexec export USE_LXC=1 cd /path/to/gitian-builder -./libexec/make-clean-vm --suite trusty --arch amd64 +./libexec/make-clean-vm --suite bionic --arch amd64 -LXC_ARCH=amd64 LXC_SUITE=trusty on-target -u root apt-get update -LXC_ARCH=amd64 LXC_SUITE=trusty on-target -u root \ +LXC_ARCH=amd64 LXC_SUITE=bionic on-target -u root apt-get update +LXC_ARCH=amd64 LXC_SUITE=bionic on-target -u root \ -e DEBIAN_FRONTEND=noninteractive apt-get --no-install-recommends -y install \ $( sed -ne '/^packages:/,/[^-] .*/ {/^- .*/{s/"//g;s/- //;p}}' ../absolute/contrib/gitian-descriptors/*|sort|uniq ) -LXC_ARCH=amd64 LXC_SUITE=trusty on-target -u root apt-get -q -y purge grub -LXC_ARCH=amd64 LXC_SUITE=trusty on-target -u root -e DEBIAN_FRONTEND=noninteractive apt-get -y dist-upgrade +LXC_ARCH=amd64 LXC_SUITE=bionic on-target -u root apt-get -q -y purge grub +LXC_ARCH=amd64 LXC_SUITE=bionic on-target -u root -e DEBIAN_FRONTEND=noninteractive apt-get -y dist-upgrade ``` And then set offline mode for apt-cacher-ng: From c292b642497705a299060105909ca382d477a1af Mon Sep 17 00:00:00 2001 From: gladcow Date: Tue, 21 Aug 2018 17:07:32 +0300 Subject: [PATCH 044/282] fix missed format parameter (#2229) --- src/masternode-payments.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/masternode-payments.cpp b/src/masternode-payments.cpp index e353b155db91..667f7ea8dc44 100644 --- a/src/masternode-payments.cpp +++ b/src/masternode-payments.cpp @@ -862,7 +862,7 @@ bool CMasternodePayments::ProcessBlock(int nBlockHeight, CConnman& connman) ExtractDestination(payee, address1); CBitcoinAddress address2(address1); - LogPrintf("CMasternodePayments::%s -- vote: payee=%s, nBlockHeight=%d\n", address2.ToString(), nBlockHeight); + LogPrintf("CMasternodePayments::%s -- vote: payee=%s, nBlockHeight=%d\n", __func__, address2.ToString(), nBlockHeight); // SIGN MESSAGE TO NETWORK WITH OUR MASTERNODE KEYS From 264410407c7ee95c53022edf03242192d32cc20b Mon Sep 17 00:00:00 2001 From: PastaPastaPasta Date: Tue, 21 Aug 2018 09:07:54 -0500 Subject: [PATCH 045/282] adds rpc calls for `setprivatesendrounds` and `setprivatesendamount` (#2230) * adds rpc calls for `setprivatesendrounds` and `setprivatesendamount` * tabs -> spaces * @gladcow change request * Whops tab -> spaces * @Udjin changes, not the CAmount -> int * int stuff * Throw error when rounds / amount isn't within range --- src/rpc/client.cpp | 2 ++ src/wallet/rpcwallet.cpp | 57 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 59 insertions(+) diff --git a/src/rpc/client.cpp b/src/rpc/client.cpp index df5a9d3445ea..9ca8445a7f62 100644 --- a/src/rpc/client.cpp +++ b/src/rpc/client.cpp @@ -140,6 +140,8 @@ static const CRPCConvertParam vRPCConvertParams[] = { "setban", 3, "absolute" }, { "setbip69enabled", 0, "enabled" }, { "setnetworkactive", 0, "state" }, + { "setprivatesendrounds", 0, "rounds" }, + { "setprivatesendamount", 0, "amount" }, { "getmempoolancestors", 1, "verbose" }, { "getmempooldescendants", 1, "verbose" }, { "spork", 1, "value" }, diff --git a/src/wallet/rpcwallet.cpp b/src/wallet/rpcwallet.cpp index f681603d568f..43ef4dfa0652 100644 --- a/src/wallet/rpcwallet.cpp +++ b/src/wallet/rpcwallet.cpp @@ -22,6 +22,7 @@ #include "wallet.h" #include "walletdb.h" #include "keepass.h" +#include "privatesend-client.h" #include @@ -2365,6 +2366,60 @@ UniValue settxfee(const JSONRPCRequest& request) return true; } +UniValue setprivatesendrounds(const JSONRPCRequest& request) +{ + if (!EnsureWalletIsAvailable(request.fHelp)) + return NullUniValue; + + if (request.fHelp || request.params.size() != 1) + throw std::runtime_error( + "setprivatesendrounds rounds\n" + "\nSet the number of rounds for PrivateSend mixing.\n" + "\nArguments:\n" + "1. rounds (numeric, required) The default number of rounds is " + std::to_string(DEFAULT_PRIVATESEND_ROUNDS) + + " Cannot be more than " + std::to_string(MAX_PRIVATESEND_ROUNDS) + " nor less than " + std::to_string(MIN_PRIVATESEND_ROUNDS) + + "\nExamples:\n" + + HelpExampleCli("setprivatesendrounds", "4") + + HelpExampleRpc("setprivatesendrounds", "16") + ); + + int nRounds = request.params[0].get_int(); + + if (nRounds > MAX_PRIVATESEND_ROUNDS || nRounds < MIN_PRIVATESEND_ROUNDS) + throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid number of rounds"); + + privateSendClient.nPrivateSendRounds = nRounds; + + return NullUniValue; +} + +UniValue setprivatesendamount(const JSONRPCRequest& request) +{ + if (!EnsureWalletIsAvailable(request.fHelp)) + return NullUniValue; + + if (request.fHelp || request.params.size() != 1) + throw std::runtime_error( + "setprivatesendamount amount\n" + "\nSet the goal amount in " + CURRENCY_UNIT + " for PrivateSend mixing.\n" + "\nArguments:\n" + "1. amount (numeric, required) The default amount is " + std::to_string(DEFAULT_PRIVATESEND_AMOUNT) + + " Cannot be more than " + std::to_string(MAX_PRIVATESEND_AMOUNT) + " nor less than " + std::to_string(MIN_PRIVATESEND_AMOUNT) + + "\nExamples:\n" + + HelpExampleCli("setprivatesendamount", "500") + + HelpExampleRpc("setprivatesendamount", "208") + ); + + int nAmount = request.params[0].get_int(); + + if (nAmount > MAX_PRIVATESEND_AMOUNT || nAmount < MIN_PRIVATESEND_AMOUNT) + throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid amount of " + CURRENCY_UNIT + " as mixing goal amount"); + + privateSendClient.nPrivateSendAmount = nAmount; + + return NullUniValue; +} + UniValue getwalletinfo(const JSONRPCRequest& request) { if (!EnsureWalletIsAvailable(request.fHelp)) @@ -2888,6 +2943,8 @@ static const CRPCCommand commands[] = { "wallet", "sendtoaddress", &sendtoaddress, false, {"address","amount","comment","comment_to","subtractfeefromamount"} }, { "wallet", "setaccount", &setaccount, true, {"address","account"} }, { "wallet", "settxfee", &settxfee, true, {"amount"} }, + { "wallet", "setprivatesendrounds", &setprivatesendrounds, true, {"rounds"} }, + { "wallet", "setprivatesendamount", &setprivatesendamount, true, {"amount"} }, { "wallet", "signmessage", &signmessage, true, {"address","message"} }, { "wallet", "walletlock", &walletlock, true, {} }, { "wallet", "walletpassphrasechange", &walletpassphrasechange, true, {"oldpassphrase","newpassphrase"} }, From a737b0b858eb5e20bbb411eb63863d88f50df0f0 Mon Sep 17 00:00:00 2001 From: Nathan Marley Date: Tue, 21 Aug 2018 07:08:11 -0700 Subject: [PATCH 046/282] add compressed option to `masternode genkey` (#2232) * add compressed option to `masternode genkey` * use ParseBoolV method * adjust help message for masternode genkey --- src/rpc/masternode.cpp | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/src/rpc/masternode.cpp b/src/rpc/masternode.cpp index c3b3ed6930f0..990c9513378f 100644 --- a/src/rpc/masternode.cpp +++ b/src/rpc/masternode.cpp @@ -145,7 +145,7 @@ UniValue masternode(const JSONRPCRequest& request) "\nAvailable commands:\n" " count - Get information about number of masternodes (DEPRECATED options: 'total', 'ps', 'enabled', 'qualify', 'all')\n" " current - Print info on current masternode winner to be paid the next block (calculated locally)\n" - " genkey - Generate new masternodeprivkey\n" + " genkey - Generate new masternodeprivkey, optional param: 'compressed' (boolean, optional, default=false) generate compressed privkey\n" #ifdef ENABLE_WALLET " outputs - Print masternode compatible (unlocked) outputs\n" " start-alias - Start single remote masternode by assigned alias configured in masternode.conf\n" @@ -375,8 +375,13 @@ UniValue masternode(const JSONRPCRequest& request) if (strCommand == "genkey") { + bool fCompressed = false; + if (request.params.size() > 1) { + fCompressed = ParseBoolV(request.params[1], "compressed"); + } + CKey secret; - secret.MakeNewKey(false); + secret.MakeNewKey(fCompressed); return CBitcoinSecret(secret).ToString(); } From 6994863e6e1169a6c498b02306ccd3448bf11343 Mon Sep 17 00:00:00 2001 From: gladcow Date: Tue, 21 Aug 2018 17:08:42 +0300 Subject: [PATCH 047/282] Fix mninfo search by payee (#2233) --- src/masternodeman.cpp | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/src/masternodeman.cpp b/src/masternodeman.cpp index 18ff95e43db1..5a64bd3c23d3 100644 --- a/src/masternodeman.cpp +++ b/src/masternodeman.cpp @@ -494,7 +494,14 @@ bool CMasternodeMan::GetMasternodeInfo(const CScript& payee, masternode_info_t& if (!ExtractDestination(payee, dest) || !boost::get(&dest)) return false; CKeyID keyId = *boost::get(&dest); - return GetMasternodeInfo(keyId, mnInfoRet); + LOCK(cs); + for (const auto& mnpair : mapMasternodes) { + if (mnpair.second.keyIDCollateralAddress == keyId) { + mnInfoRet = mnpair.second.GetInfo(); + return true; + } + } + return false; } bool CMasternodeMan::Has(const COutPoint& outpoint) From 8fec95063c07565192dca011cc0a3c183286a3e7 Mon Sep 17 00:00:00 2001 From: Alexander Block Date: Tue, 21 Aug 2018 17:34:26 +0200 Subject: [PATCH 048/282] Don't crash when formatting in logging throws exceptions (#2231) * Don't crash when formatting in logging throws exceptions * Preserve exception like output --- src/util.h | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/src/util.h b/src/util.h index 5c4e4f7122a6..7a3c20af1200 100644 --- a/src/util.h +++ b/src/util.h @@ -98,20 +98,33 @@ bool LogAcceptCategory(const char* category); /** Send a string to the log output */ int LogPrintStr(const std::string &str); +/** Formats a string without throwing exceptions. Instead, it'll return an error string instead of formatted string. */ +template +std::string SafeStringFormat(const std::string& fmt, const Args&... args) +{ + try { + return tinyformat::format(fmt, args...); + } catch (std::runtime_error& e) { + std::string message = tinyformat::format("\n****TINYFORMAT ERROR****\n err=\"%s\"\n fmt=\"%s\"\n", e.what(), fmt); + fprintf(stderr, "%s", message.c_str()); + return message; + } +} + #define LogPrint(category, ...) do { \ if (LogAcceptCategory((category))) { \ - LogPrintStr(tinyformat::format(__VA_ARGS__)); \ + LogPrintStr(SafeStringFormat(__VA_ARGS__)); \ } \ } while(0) #define LogPrintf(...) do { \ - LogPrintStr(tinyformat::format(__VA_ARGS__)); \ + LogPrintStr(SafeStringFormat(__VA_ARGS__)); \ } while(0) template bool error(const char* fmt, const Args&... args) { - LogPrintStr("ERROR: " + tinyformat::format(fmt, args...) + "\n"); + LogPrintStr("ERROR: " + SafeStringFormat(fmt, args...) + "\n"); return false; } From 28f0a97b21fc232c454c171723188c6bcd33e41e Mon Sep 17 00:00:00 2001 From: Alexander Block Date: Mon, 27 Aug 2018 14:48:45 +0200 Subject: [PATCH 049/282] Revert CMasternodePayments::IsTransactionValid to the logic before the recent refactorings (#2237) partially reverts #2216 --- src/masternode-payments.cpp | 27 +++------------------------ 1 file changed, 3 insertions(+), 24 deletions(-) diff --git a/src/masternode-payments.cpp b/src/masternode-payments.cpp index 667f7ea8dc44..d034fd8fb663 100644 --- a/src/masternode-payments.cpp +++ b/src/masternode-payments.cpp @@ -707,30 +707,9 @@ std::string CMasternodePayments::GetRequiredPaymentsString(int nBlockHeight) con bool CMasternodePayments::IsTransactionValid(const CTransaction& txNew, int nBlockHeight, CAmount blockReward) const { - std::vector voutMasternodePayments; - if (!GetBlockTxOuts(nBlockHeight, blockReward, voutMasternodePayments)) { - LogPrintf("CMasternodePayments::%s -- ERROR failed to get payees for block at height %s\n", __func__, nBlockHeight); - return false; - } - - for (const auto& txout : voutMasternodePayments) { - bool found = false; - for (const auto& txout2 : txNew.vout) { - if (txout == txout2) { - found = true; - break; - } - } - if (!found) { - CTxDestination dest; - if (!ExtractDestination(txout.scriptPubKey, dest)) - assert(false); - LogPrintf("CMasternodePayments::%s -- ERROR failed to find expected payee %s in block at height %s\n", __func__, CBitcoinAddress(dest).ToString(), nBlockHeight); - return false; - } - } - - return true; + LOCK(cs_mapMasternodeBlocks); + const auto it = mapMasternodeBlocks.find(nBlockHeight); + return it == mapMasternodeBlocks.end() ? true : it->second.IsTransactionValid(txNew); } void CMasternodePayments::CheckAndRemove() From 838e15fe5cdacff254d6dae238a71a22f3c61135 Mon Sep 17 00:00:00 2001 From: Alexander Block Date: Tue, 28 Aug 2018 13:43:58 +0200 Subject: [PATCH 050/282] Move DIP1 transaction size checks out of ContextualCheckBlock and use ContextualCheckTransaction instead (#2238) * Pass consensus params to ContextualCheckTransaction As we do with ContextualCheckBlock * Use ContextualCheckTransaction in ContextualCheckBlock instead of duplicating the check * Fix pindexPrev parameter signature in ContextualCheckTransaction --- src/validation.cpp | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/validation.cpp b/src/validation.cpp index 2498eade8fa8..4c1b23645c9f 100644 --- a/src/validation.cpp +++ b/src/validation.cpp @@ -578,10 +578,10 @@ bool CheckTransaction(const CTransaction& tx, CValidationState &state) return true; } -bool ContextualCheckTransaction(const CTransaction& tx, CValidationState &state, CBlockIndex * const pindexPrev) +bool ContextualCheckTransaction(const CTransaction& tx, CValidationState &state, const Consensus::Params& consensusParams, const CBlockIndex* pindexPrev) { int nHeight = pindexPrev == NULL ? 0 : pindexPrev->nHeight + 1; - bool fDIP0001Active_context = nHeight >= Params().GetConsensus().DIP0001Height; + bool fDIP0001Active_context = nHeight >= consensusParams.DIP0001Height; // Size limits if (fDIP0001Active_context && ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION) > MAX_STANDARD_TX_SIZE) @@ -636,7 +636,7 @@ bool AcceptToMemoryPoolWorker(CTxMemPool& pool, CValidationState& state, const C if (!CheckTransaction(tx, state)) return false; // state filled in by CheckTransaction - if (!ContextualCheckTransaction(tx, state, chainActive.Tip())) + if (!ContextualCheckTransaction(tx, state, Params().GetConsensus(), chainActive.Tip())) return error("%s: ContextualCheckTransaction: %s, %s", __func__, hash.ToString(), FormatStateMessage(state)); // Coinbase is only valid in a block, not as a loose transaction @@ -3478,8 +3478,8 @@ bool ContextualCheckBlock(const CBlock& block, CValidationState& state, const Co if (!IsFinalTx(*tx, nHeight, nLockTimeCutoff)) { return state.DoS(10, false, REJECT_INVALID, "bad-txns-nonfinal", false, "non-final transaction"); } - if (fDIP0001Active_context && ::GetSerializeSize(*tx, SER_NETWORK, PROTOCOL_VERSION) > MAX_STANDARD_TX_SIZE) { - return state.DoS(10, false, REJECT_INVALID, "bad-txns-oversized", false, "contains an over-sized transaction"); + if (!ContextualCheckTransaction(*tx, state, consensusParams, pindexPrev)) { + return false; } nSigOps += GetLegacySigOpCount(*tx); } From 99bef66eeb7d99203b0cca48248607366a50d6ac Mon Sep 17 00:00:00 2001 From: CryptoCentric Date: Thu, 25 Apr 2019 18:48:13 +0100 Subject: [PATCH 051/282] Deployment of AIP0003 --- src/chainparams.cpp | 10 ++++++++++ src/consensus/params.h | 1 + src/dsnotificationinterface.cpp | 1 + src/init.cpp | 5 +++++ src/rpc/blockchain.cpp | 1 + src/validation.cpp | 10 ++++++++++ src/validation.h | 2 ++ src/versionbits.cpp | 5 +++++ 8 files changed, 35 insertions(+) diff --git a/src/chainparams.cpp b/src/chainparams.cpp index 95dca10b0936..4c957332e1f6 100644 --- a/src/chainparams.cpp +++ b/src/chainparams.cpp @@ -458,6 +458,13 @@ class CPoVNETParams : public CChainParams { consensus.vDeployments[Consensus::DEPLOYMENT_BIP147].nWindowSize = 100; consensus.vDeployments[Consensus::DEPLOYMENT_BIP147].nThreshold = 50; // 50% of 100 + // Deployment of AIP0003 + consensus.vDeployments[Consensus::DEPLOYMENT_AIP0003].bit = 3; + consensus.vDeployments[Consensus::DEPLOYMENT_AIP0003].nStartTime = 1556150400; // Thursday, 25-Apr-19 00:00:00 UTC + consensus.vDeployments[Consensus::DEPLOYMENT_AIP0003].nTimeout = 1587772800; // Saturday, 25-Apr-20 00:00:00 UTC + consensus.vDeployments[Consensus::DEPLOYMENT_AIP0003].nWindowSize = 100; + consensus.vDeployments[Consensus::DEPLOYMENT_AIP0003].nThreshold = 50; // 50% of 100 + // The best chain should have at least this much work. consensus.nMinimumChainWork = uint256S("0x000000000000000000000000000000000000000000000000000000000000000"); @@ -574,6 +581,9 @@ class CRegTestParams : public CChainParams { consensus.vDeployments[Consensus::DEPLOYMENT_BIP147].bit = 2; consensus.vDeployments[Consensus::DEPLOYMENT_BIP147].nStartTime = 0; consensus.vDeployments[Consensus::DEPLOYMENT_BIP147].nTimeout = 999999999999ULL; + consensus.vDeployments[Consensus::DEPLOYMENT_AIP0003].bit = 3; + consensus.vDeployments[Consensus::DEPLOYMENT_AIP0003].nStartTime = 0; + consensus.vDeployments[Consensus::DEPLOYMENT_AIP0003].nTimeout = 999999999999ULL; // The best chain should have at least this much work. consensus.nMinimumChainWork = uint256S("0x00"); diff --git a/src/consensus/params.h b/src/consensus/params.h index 5dfda9a3467c..3c3ba773acb2 100644 --- a/src/consensus/params.h +++ b/src/consensus/params.h @@ -18,6 +18,7 @@ enum DeploymentPos DEPLOYMENT_CSV, // Deployment of BIP68, BIP112, and BIP113. DEPLOYMENT_DIP0001, // Deployment of DIP0001 and lower transaction fees. DEPLOYMENT_BIP147, // Deployment of BIP147 (NULLDUMMY) + DEPLOYMENT_AIP0003, // Deployment of DIP0002 and AIP0003 (txv3 and deterministic MN lists) // NOTE: Also add new deployments to VersionBitsDeploymentInfo in versionbits.cpp MAX_VERSION_BITS_DEPLOYMENTS }; diff --git a/src/dsnotificationinterface.cpp b/src/dsnotificationinterface.cpp index 90d572aa0b15..58bb34bf496e 100644 --- a/src/dsnotificationinterface.cpp +++ b/src/dsnotificationinterface.cpp @@ -40,6 +40,7 @@ void CDSNotificationInterface::UpdatedBlockTip(const CBlockIndex *pindexNew, con // Update global DIP0001 activation status fDIP0001ActiveAtTip = pindexNew->nHeight >= Params().GetConsensus().DIP0001Height; + fAIP0003ActiveAtTip = (VersionBitsState(pindexNew->pprev, Params().GetConsensus(), Consensus::DEPLOYMENT_AIP0003, versionbitscache) == THRESHOLD_ACTIVE); if (fInitialDownload) return; diff --git a/src/init.cpp b/src/init.cpp index 6177b9e7a4d9..cb4de66b1aad 100644 --- a/src/init.cpp +++ b/src/init.cpp @@ -1670,6 +1670,11 @@ bool AppInitMain(boost::thread_group& threadGroup, CScheduler& scheduler) break; } + // Needs to be called after chain is initialized + if (chainActive.Tip() && chainActive.Tip()->pprev) { + fAIP0003ActiveAtTip = VersionBitsState(chainActive.Tip()->pprev, Params().GetConsensus(), Consensus::DEPLOYMENT_AIP0003, versionbitscache) == THRESHOLD_ACTIVE; + } + uiInterface.InitMessage(_("Verifying blocks...")); if (fHavePruned && GetArg("-checkblocks", DEFAULT_CHECKBLOCKS) > MIN_BLOCKS_TO_KEEP) { LogPrintf("Prune: pruned datadir may not have more than %d blocks; only checking available blocks", diff --git a/src/rpc/blockchain.cpp b/src/rpc/blockchain.cpp index fe6162d34fc7..50083ee5c8df 100644 --- a/src/rpc/blockchain.cpp +++ b/src/rpc/blockchain.cpp @@ -1283,6 +1283,7 @@ UniValue getblockchaininfo(const JSONRPCRequest& request) softforks.push_back(SoftForkDesc("bip65", 4, tip, consensusParams)); BIP9SoftForkDescPushBack(bip9_softforks, "csv", consensusParams, Consensus::DEPLOYMENT_CSV); BIP9SoftForkDescPushBack(bip9_softforks, "dip0001", consensusParams, Consensus::DEPLOYMENT_DIP0001); + BIP9SoftForkDescPushBack(bip9_softforks, "AIP0003", consensusParams, Consensus::DEPLOYMENT_AIP0003); BIP9SoftForkDescPushBack(bip9_softforks, "bip147", consensusParams, Consensus::DEPLOYMENT_BIP147); obj.push_back(Pair("softforks", softforks)); obj.push_back(Pair("bip9_softforks", bip9_softforks)); diff --git a/src/validation.cpp b/src/validation.cpp index 4c1b23645c9f..b664e310720a 100644 --- a/src/validation.cpp +++ b/src/validation.cpp @@ -92,6 +92,7 @@ int64_t nMaxTipAge = DEFAULT_MAX_TIP_AGE; bool fEnableReplacement = DEFAULT_ENABLE_REPLACEMENT; std::atomic fDIP0001ActiveAtTip{false}; +std::atomic fAIP0003ActiveAtTip{false}; uint256 hashAssumeValid; @@ -1896,6 +1897,9 @@ static DisconnectResult DisconnectBlock(const CBlock& block, CValidationState& s } } + if (pindex->pprev && pindex->pprev->pprev && VersionBitsState(pindex->pprev->pprev, Params().GetConsensus(), Consensus::DEPLOYMENT_AIP0003, versionbitscache) != THRESHOLD_ACTIVE) { + fAIP0003ActiveAtTip = false; + } // move best block pointer to prevout block view.SetBestBlock(pindex->pprev->GetBlockHash()); @@ -2164,6 +2168,12 @@ static bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockInd flags |= SCRIPT_VERIFY_NULLDUMMY; } + if (!fJustCheck && VersionBitsState(pindex->pprev, chainparams.GetConsensus(), Consensus::DEPLOYMENT_AIP0003, versionbitscache) == THRESHOLD_ACTIVE) { + if (!fAIP0003ActiveAtTip) + LogPrintf("ConnectBlock -- AIP0003 got activated at height %d\n", pindex->nHeight); + fAIP0003ActiveAtTip = true; + } + int64_t nTime2 = GetTimeMicros(); nTimeForks += nTime2 - nTime1; LogPrint("bench", " - Fork checks: %.2fms [%.2fs]\n", 0.001 * (nTime2 - nTime1), nTimeForks * 0.000001); diff --git a/src/validation.h b/src/validation.h index 52d0e229a0da..cc1980c1d66b 100644 --- a/src/validation.h +++ b/src/validation.h @@ -188,6 +188,8 @@ extern bool fLargeWorkInvalidChainFound; extern std::map mapRejectedBlocks; extern std::atomic fDIP0001ActiveAtTip; +extern std::atomic fAIP0003ActiveAtTip; + /** Block hash whose ancestors we will assume to have valid scripts without checking them. */ extern uint256 hashAssumeValid; diff --git a/src/versionbits.cpp b/src/versionbits.cpp index af37b6350ae3..ddd2f1f755a9 100644 --- a/src/versionbits.cpp +++ b/src/versionbits.cpp @@ -26,6 +26,11 @@ const struct BIP9DeploymentInfo VersionBitsDeploymentInfo[Consensus::MAX_VERSION /*.name =*/ "bip147", /*.gbt_force =*/ true, /*.check_mn_protocol =*/ false, + }, + { + /*.name =*/ "AIP0003", + /*.gbt_force =*/ true, + /*.check_mn_protocol =*/ false, } }; From 8d67125641beeb48e1c42f384c8e4e336d473323 Mon Sep 17 00:00:00 2001 From: CryptoCentric Date: Thu, 25 Apr 2019 18:49:31 +0100 Subject: [PATCH 052/282] AIP2 CTransaction and CMutableTransaction --- src/consensus/consensus.h | 2 ++ src/primitives/transaction.cpp | 22 +++++++++++++--------- src/primitives/transaction.h | 30 +++++++++++++++++++++++++----- src/rpc/rawtransaction.cpp | 7 +++++++ src/script/interpreter.cpp | 5 ++++- 5 files changed, 51 insertions(+), 15 deletions(-) diff --git a/src/consensus/consensus.h b/src/consensus/consensus.h index d53a551bb48d..46c4c147b8c1 100644 --- a/src/consensus/consensus.h +++ b/src/consensus/consensus.h @@ -18,6 +18,8 @@ inline unsigned int MaxBlockSigOps(bool fDIP0001Active /*= false */) { return MaxBlockSize(fDIP0001Active) / 50; } +/** The maximum allowed size of version 3 extra payload */ +static const unsigned int MAX_TX_EXTRA_PAYLOAD = 10000; /** Coinbase transaction outputs can only be spent after this number of new blocks (network rule) */ static const int COINBASE_MATURITY = 50; diff --git a/src/primitives/transaction.cpp b/src/primitives/transaction.cpp index f2afae047c8e..892cec4f690a 100644 --- a/src/primitives/transaction.cpp +++ b/src/primitives/transaction.cpp @@ -60,8 +60,8 @@ std::string CTxOut::ToString() const return strprintf("CTxOut(nValue=%d.%08d, scriptPubKey=%s)", nValue / COIN, nValue % COIN, HexStr(scriptPubKey).substr(0, 30)); } -CMutableTransaction::CMutableTransaction() : nVersion(CTransaction::CURRENT_VERSION), nLockTime(0) {} -CMutableTransaction::CMutableTransaction(const CTransaction& tx) : nVersion(tx.nVersion), vin(tx.vin), vout(tx.vout), nLockTime(tx.nLockTime) {} +CMutableTransaction::CMutableTransaction() : nVersion(CTransaction::CURRENT_VERSION), nType(TRANSACTION_NORMAL), nLockTime(0) {} +CMutableTransaction::CMutableTransaction(const CTransaction& tx) : nVersion(tx.nVersion), nType(tx.nType), vin(tx.vin), vout(tx.vout), nLockTime(tx.nLockTime), vExtraPayload(tx.vExtraPayload) {} uint256 CMutableTransaction::GetHash() const { @@ -71,12 +71,14 @@ uint256 CMutableTransaction::GetHash() const std::string CMutableTransaction::ToString() const { std::string str; - str += strprintf("CMutableTransaction(hash=%s, ver=%d, vin.size=%u, vout.size=%u, nLockTime=%u)\n", + str += strprintf("CMutableTransaction(hash=%s, ver=%d, type=%d, vin.size=%u, vout.size=%u, nLockTime=%u, vExtraPayload.size=%d)\n", GetHash().ToString().substr(0,10), nVersion, + nType, vin.size(), vout.size(), - nLockTime); + nLockTime, + vExtraPayload.size()); for (unsigned int i = 0; i < vin.size(); i++) str += " " + vin[i].ToString() + "\n"; for (unsigned int i = 0; i < vout.size(); i++) @@ -90,9 +92,9 @@ uint256 CTransaction::ComputeHash() const } /* For backward compatibility, the hash is initialized to 0. TODO: remove the need for this default constructor entirely. */ -CTransaction::CTransaction() : nVersion(CTransaction::CURRENT_VERSION), vin(), vout(), nLockTime(0), hash() {} -CTransaction::CTransaction(const CMutableTransaction &tx) : nVersion(tx.nVersion), vin(tx.vin), vout(tx.vout), nLockTime(tx.nLockTime), hash(ComputeHash()) {} -CTransaction::CTransaction(CMutableTransaction &&tx) : nVersion(tx.nVersion), vin(std::move(tx.vin)), vout(std::move(tx.vout)), nLockTime(tx.nLockTime), hash(ComputeHash()) {} +CTransaction::CTransaction() : nVersion(CTransaction::CURRENT_VERSION), nType(TRANSACTION_NORMAL), vin(), vout(), nLockTime(0), hash() {} +CTransaction::CTransaction(const CMutableTransaction &tx) : nVersion(tx.nVersion), nType(tx.nType), vin(tx.vin), vout(tx.vout), nLockTime(tx.nLockTime), vExtraPayload(tx.vExtraPayload), hash(ComputeHash()) {} +CTransaction::CTransaction(CMutableTransaction &&tx) : nVersion(tx.nVersion), nType(tx.nType), vin(std::move(tx.vin)), vout(std::move(tx.vout)), nLockTime(tx.nLockTime), vExtraPayload(tx.vExtraPayload), hash(ComputeHash()) {} CAmount CTransaction::GetValueOut() const { @@ -140,12 +142,14 @@ unsigned int CTransaction::GetTotalSize() const std::string CTransaction::ToString() const { std::string str; - str += strprintf("CTransaction(hash=%s, ver=%d, vin.size=%u, vout.size=%u, nLockTime=%u)\n", + str += strprintf("CTransaction(hash=%s, ver=%d, type=%d, vin.size=%u, vout.size=%u, nLockTime=%u, vExtraPayload.size=%d)\n", GetHash().ToString().substr(0,10), nVersion, + nType, vin.size(), vout.size(), - nLockTime); + nLockTime, + vExtraPayload.size()); for (unsigned int i = 0; i < vin.size(); i++) str += " " + vin[i].ToString() + "\n"; for (unsigned int i = 0; i < vout.size(); i++) diff --git a/src/primitives/transaction.h b/src/primitives/transaction.h index b14e5b261d74..f383d0b3c557 100644 --- a/src/primitives/transaction.h +++ b/src/primitives/transaction.h @@ -11,6 +11,11 @@ #include "serialize.h" #include "uint256.h" +/** Transaction types */ +enum { + TRANSACTION_NORMAL = 0, +}; + /** An outpoint - a combination of a transaction hash and an index n into its vout */ class COutPoint { @@ -215,17 +220,19 @@ class CTransaction // adapting relay policy by bumping MAX_STANDARD_VERSION, and then later date // bumping the default CURRENT_VERSION at which point both CURRENT_VERSION and // MAX_STANDARD_VERSION will be equal. - static const int32_t MAX_STANDARD_VERSION=2; + static const int32_t MAX_STANDARD_VERSION=3; // The local variables are made const to prevent unintended modification // without updating the cached hash value. However, CTransaction is not // actually immutable; deserialization and assignment are implemented, // and bypass the constness. This is safe, as they update the entire // structure, including the hash. - const int32_t nVersion; + const int16_t nVersion; + const int16_t nType; const std::vector vin; const std::vector vout; const uint32_t nLockTime; + const std::vector vExtraPayload; // only available for special transaction types private: /** Memory only. */ @@ -243,10 +250,13 @@ class CTransaction template inline void Serialize(Stream& s) const { - s << this->nVersion; + int32_t n32bitVersion = this->nVersion | (this->nType << 16); + s << n32bitVersion; s << vin; s << vout; s << nLockTime; + if (this->nVersion >= 3 && this->nType != TRANSACTION_NORMAL) + s << vExtraPayload; } /** This deserializing constructor is provided instead of an Unserialize method. @@ -301,10 +311,12 @@ class CTransaction /** A mutable version of CTransaction. */ struct CMutableTransaction { - int32_t nVersion; + int16_t nVersion; + int16_t nType; std::vector vin; std::vector vout; uint32_t nLockTime; + std::vector vExtraPayload; // only available for special transaction types CMutableTransaction(); CMutableTransaction(const CTransaction& tx); @@ -313,10 +325,18 @@ struct CMutableTransaction template inline void SerializationOp(Stream& s, Operation ser_action) { - READWRITE(this->nVersion); + int32_t n32bitVersion = this->nVersion | (this->nType << 16); + READWRITE(n32bitVersion); + if (ser_action.ForRead()) { + this->nVersion = (int16_t) (n32bitVersion & 0xffff); + this->nType = (int16_t) ((n32bitVersion >> 16) & 0xffff); + } READWRITE(vin); READWRITE(vout); READWRITE(nLockTime); + if (this->nVersion >= 3 && this->nType != TRANSACTION_NORMAL) { + READWRITE(vExtraPayload); + } } template diff --git a/src/rpc/rawtransaction.cpp b/src/rpc/rawtransaction.cpp index 0a2e1cee16db..220a8eea1e88 100644 --- a/src/rpc/rawtransaction.cpp +++ b/src/rpc/rawtransaction.cpp @@ -66,6 +66,7 @@ void TxToJSON(const CTransaction& tx, const uint256 hashBlock, UniValue& entry) entry.push_back(Pair("txid", txid.GetHex())); entry.push_back(Pair("size", (int)::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION))); entry.push_back(Pair("version", tx.nVersion)); + entry.push_back(Pair("type", tx.nType)); entry.push_back(Pair("locktime", (int64_t)tx.nLockTime)); UniValue vin(UniValue::VARR); BOOST_FOREACH(const CTxIn& txin, tx.vin) { @@ -122,6 +123,11 @@ void TxToJSON(const CTransaction& tx, const uint256 hashBlock, UniValue& entry) } entry.push_back(Pair("vout", vout)); + if (!tx.vExtraPayload.empty()) { + entry.push_back(Pair("extraPayloadSize", (int)tx.vExtraPayload.size())); + entry.push_back(Pair("extraPayload", HexStr(tx.vExtraPayload))); + } + if (!hashBlock.IsNull()) { entry.push_back(Pair("blockhash", hashBlock.GetHex())); BlockMap::iterator mi = mapBlockIndex.find(hashBlock); @@ -499,6 +505,7 @@ UniValue decoderawtransaction(const JSONRPCRequest& request) " \"txid\" : \"id\", (string) The transaction id\n" " \"size\" : n, (numeric) The transaction size\n" " \"version\" : n, (numeric) The version\n" + " \"type\" : n, (numeric) The type\n" " \"locktime\" : ttt, (numeric) The lock time\n" " \"vin\" : [ (array of json objects)\n" " {\n" diff --git a/src/script/interpreter.cpp b/src/script/interpreter.cpp index 2aafa9759efe..4fd2f69c3292 100644 --- a/src/script/interpreter.cpp +++ b/src/script/interpreter.cpp @@ -1097,7 +1097,8 @@ class CTransactionSignatureSerializer { template void Serialize(S &s) const { // Serialize nVersion - ::Serialize(s, txTo.nVersion); + int32_t n32bitVersion = txTo.nVersion | (txTo.nType << 16); + ::Serialize(s, n32bitVersion); // Serialize vin unsigned int nInputs = fAnyoneCanPay ? 1 : txTo.vin.size(); ::WriteCompactSize(s, nInputs); @@ -1110,6 +1111,8 @@ class CTransactionSignatureSerializer { SerializeOutput(s, nOutput); // Serialize nLockTime ::Serialize(s, txTo.nLockTime); + if (txTo.nVersion >= 3 && txTo.nType != TRANSACTION_NORMAL) + ::Serialize(s, txTo.vExtraPayload); } }; From c93fd5a571aa8f308b64b67efaa00967e590be6b Mon Sep 17 00:00:00 2001 From: CryptoCentric Date: Thu, 25 Apr 2019 18:51:56 +0100 Subject: [PATCH 053/282] Validation of version 3 TXs CheckTransaction --- src/validation.cpp | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/src/validation.cpp b/src/validation.cpp index b664e310720a..ed1d80ce63cf 100644 --- a/src/validation.cpp +++ b/src/validation.cpp @@ -521,6 +521,8 @@ bool CheckTransaction(const CTransaction& tx, CValidationState &state) // Size limits if (::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION) > MAX_LEGACY_BLOCK_SIZE) return state.DoS(100, false, REJECT_INVALID, "bad-txns-oversize"); + if (tx.vExtraPayload.size() > MAX_TX_EXTRA_PAYLOAD) + return state.DoS(100, false, REJECT_INVALID, "bad-txns-payload-oversize"); // Check for negative or overflow output values CAmount nValueOut = 0; @@ -583,6 +585,20 @@ bool ContextualCheckTransaction(const CTransaction& tx, CValidationState &state, { int nHeight = pindexPrev == NULL ? 0 : pindexPrev->nHeight + 1; bool fDIP0001Active_context = nHeight >= consensusParams.DIP0001Height; + bool fAIP003Active_context = VersionBitsState(pindexPrev, consensusParams, Consensus::DEPLOYMENT_AIP003, versionbitscache) == THRESHOLD_ACTIVE; + + if (fAIP003Active_context) { + // check version 3 transaction types + if (tx.nVersion >= 3) { + if (tx.nType != TRANSACTION_NORMAL) { + return state.DoS(100, false, REJECT_INVALID, "bad-txns-type"); + } + if (tx.IsCoinBase() && tx.nType != TRANSACTION_NORMAL) + return state.DoS(100, false, REJECT_INVALID, "bad-txns-cb-type"); + } else if (tx.nType != TRANSACTION_NORMAL) { + return state.DoS(100, false, REJECT_INVALID, "bad-txns-type"); + } + } // Size limits if (fDIP0001Active_context && ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION) > MAX_STANDARD_TX_SIZE) From 70078f573ac992e6cb7a5afa26db2c823a3a9586 Mon Sep 17 00:00:00 2001 From: Alexander Block Date: Tue, 13 Feb 2018 13:34:35 +0100 Subject: [PATCH 054/282] Stubs for special TX validation and processing --- src/Makefile.am | 2 ++ src/evo/specialtx.cpp | 84 +++++++++++++++++++++++++++++++++++++++++++ src/evo/specialtx.h | 19 ++++++++++ src/validation.cpp | 14 +++++++- 4 files changed, 118 insertions(+), 1 deletion(-) create mode 100644 src/evo/specialtx.cpp create mode 100644 src/evo/specialtx.h diff --git a/src/Makefile.am b/src/Makefile.am index 5c941b0c3ced..3a4917cbcd98 100644 --- a/src/Makefile.am +++ b/src/Makefile.am @@ -105,6 +105,7 @@ BITCOIN_CORE_H = \ core_io.h \ core_memusage.h \ cuckoocache.h \ + evo/specialtx.h \ privatesend.h \ privatesend-client.h \ privatesend-server.h \ @@ -215,6 +216,7 @@ libabsolute_server_a_SOURCES = \ chain.cpp \ checkpoints.cpp \ dsnotificationinterface.cpp \ + evo/specialtx.cpp \ httprpc.cpp \ httpserver.cpp \ init.cpp \ diff --git a/src/evo/specialtx.cpp b/src/evo/specialtx.cpp new file mode 100644 index 000000000000..f648f7f106be --- /dev/null +++ b/src/evo/specialtx.cpp @@ -0,0 +1,84 @@ +// Copyright (c) 2017 The Dash Core developers +// Distributed under the MIT software license, see the accompanying +// file COPYING or http://www.opensource.org/licenses/mit-license.php. + +#include "primitives/transaction.h" +#include "primitives/block.h" +#include "consensus/validation.h" +#include "hash.h" +#include "clientversion.h" +#include "validation.h" +#include "chainparams.h" + +#include "specialtx.h" + +bool CheckSpecialTx(const CTransaction& tx, const CBlockIndex* pindex, CValidationState& state) +{ + AssertLockHeld(cs_main); + + if (tx.nVersion < 3 || tx.nType == TRANSACTION_NORMAL) + return true; + + if (pindex && VersionBitsState(pindex->pprev, Params().GetConsensus(), Consensus::DEPLOYMENT_DIP0003, versionbitscache) != THRESHOLD_ACTIVE) { + return state.DoS(10, false, REJECT_INVALID, "bad-tx-type"); + } + + switch (tx.nType) { + } + + return state.DoS(10, false, REJECT_INVALID, "bad-tx-type"); +} + +bool ProcessSpecialTx(const CTransaction& tx, const CBlockIndex* pindex, CValidationState& state) +{ + if (tx.nVersion < 3 || tx.nType == TRANSACTION_NORMAL) + return true; + + switch (tx.nType) { + } + + return state.DoS(100, false, REJECT_INVALID, "bad-tx-type"); +} + +bool UndoSpecialTx(const CTransaction& tx, const CBlockIndex* pindex) +{ + if (tx.nVersion < 3 || tx.nType == TRANSACTION_NORMAL) + return true; + + switch (tx.nType) { + } + + return false; +} + +bool ProcessSpecialTxsInBlock(const CBlock& block, const CBlockIndex* pindex, CValidationState& state) +{ + for (int i = 0; i < (int)block.vtx.size(); i++) { + const CTransaction& tx = *block.vtx[i]; + if (!CheckSpecialTx(tx, pindex, state)) + return false; + if (!ProcessSpecialTx(tx, pindex, state)) + return false; + } + + return true; +} + +bool UndoSpecialTxsInBlock(const CBlock& block, const CBlockIndex* pindex) +{ + for (int i = (int)block.vtx.size() - 1; i >= 0; --i) { + const CTransaction& tx = *block.vtx[i]; + if (!UndoSpecialTx(tx, pindex)) + return false; + } + return true; +} + +uint256 CalcTxInputsHash(const CTransaction& tx) +{ + CHashWriter hw(CLIENT_VERSION, SER_GETHASH); + for (const auto& in : tx.vin) { + hw << in.prevout; + } + return hw.GetHash(); +} diff --git a/src/evo/specialtx.h b/src/evo/specialtx.h new file mode 100644 index 000000000000..2eaf2c9cc57d --- /dev/null +++ b/src/evo/specialtx.h @@ -0,0 +1,19 @@ +// Copyright (c) 2017 The Dash Core developers +// Distributed under the MIT software license, see the accompanying +// file COPYING or http://www.opensource.org/licenses/mit-license.php. + +#ifndef DASH_SPECIALTX_H +#define DASH_SPECIALTX_H + +class CTransaction; +class CBlock; +class CBlockIndex; +class CValidationState; + +bool CheckSpecialTx(const CTransaction& tx, const CBlockIndex* pindex, CValidationState& state); +bool ProcessSpecialTxsInBlock(const CBlock& block, const CBlockIndex* pindex, CValidationState& state); +bool UndoSpecialTxsInBlock(const CBlock& block, const CBlockIndex* pindex); + +uint256 CalcTxInputsHash(const CTransaction& tx); + +#endif//DASH_SPECIALTX_H diff --git a/src/validation.cpp b/src/validation.cpp index ed1d80ce63cf..71d0c8ca9235 100644 --- a/src/validation.cpp +++ b/src/validation.cpp @@ -45,6 +45,8 @@ #include "masternodeman.h" #include "masternode-payments.h" +#include "evo/specialtx.h" + #include #include @@ -656,6 +658,9 @@ bool AcceptToMemoryPoolWorker(CTxMemPool& pool, CValidationState& state, const C if (!ContextualCheckTransaction(tx, state, Params().GetConsensus(), chainActive.Tip())) return error("%s: ContextualCheckTransaction: %s, %s", __func__, hash.ToString(), FormatStateMessage(state)); + if (!CheckSpecialTx(tx, chainActive.Tip(), state)) + return false; + // Coinbase is only valid in a block, not as a loose transaction if (tx.IsCoinBase()) return state.DoS(100, false, REJECT_INVALID, "coinbase"); @@ -1802,6 +1807,10 @@ static DisconnectResult DisconnectBlock(const CBlock& block, CValidationState& s std::vector > addressUnspentIndex; std::vector > spentIndex; + if (!UndoSpecialTxsInBlock(block, pindex)) { + return DISCONNECT_FAILED; + } + // undo transactions in reverse order for (int i = block.vtx.size() - 1; i >= 0; i--) { const CTransaction &tx = *(block.vtx[i]); @@ -2347,7 +2356,10 @@ static bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockInd int64_t nTime3 = GetTimeMicros(); nTimeConnect += nTime3 - nTime2; LogPrint("bench", " - Connect %u transactions: %.2fms (%.3fms/tx, %.3fms/txin) [%.2fs]\n", (unsigned)block.vtx.size(), 0.001 * (nTime3 - nTime2), 0.001 * (nTime3 - nTime2) / block.vtx.size(), nInputs <= 1 ? 0 : 0.001 * (nTime3 - nTime2) / (nInputs-1), nTimeConnect * 0.000001); - // ABSOLUTE : MODIFIED TO CHECK MASTERNODE PAYMENTS AND SUPERBLOCKS + if (!ProcessSpecialTxsInBlock(block, pindex, state)) + return false; + + // ABSOLUTE: MODIFIED TO CHECK MASTERNODE PAYMENTS AND SUPERBLOCKS // It's possible that we simply don't have enough data and this could fail // (i.e. block itself could be a correct one and we need to store it), From 9308e3fd87c87592800d725acea8d745d0e4ea05 Mon Sep 17 00:00:00 2001 From: Alexander Block Date: Wed, 14 Feb 2018 12:05:25 +0100 Subject: [PATCH 055/282] Add Get-/SetTxPayload helpers --- src/evo/specialtx.h | 35 ++++++++++++++++++++++++++++++++++- 1 file changed, 34 insertions(+), 1 deletion(-) diff --git a/src/evo/specialtx.h b/src/evo/specialtx.h index 2eaf2c9cc57d..903380124bcc 100644 --- a/src/evo/specialtx.h +++ b/src/evo/specialtx.h @@ -5,7 +5,10 @@ #ifndef DASH_SPECIALTX_H #define DASH_SPECIALTX_H -class CTransaction; +#include "streams.h" +#include "version.h" +#include "primitives/transaction.h" + class CBlock; class CBlockIndex; class CValidationState; @@ -14,6 +17,36 @@ bool CheckSpecialTx(const CTransaction& tx, const CBlockIndex* pindex, CValidati bool ProcessSpecialTxsInBlock(const CBlock& block, const CBlockIndex* pindex, CValidationState& state); bool UndoSpecialTxsInBlock(const CBlock& block, const CBlockIndex* pindex); +template +inline bool GetTxPayload(const std::vector& payload, T& obj) +{ + CDataStream ds(payload, SER_NETWORK, PROTOCOL_VERSION); + try { + ds >> obj; + } catch (std::exception& e) { + return false; + } + return ds.empty(); +} +template +inline bool GetTxPayload(const CMutableTransaction& tx, T& obj) +{ + return GetTxPayload(tx.vExtraPayload, obj); +} +template +inline bool GetTxPayload(const CTransaction& tx, T& obj) +{ + return GetTxPayload(tx.vExtraPayload, obj); +} + +template +void SetTxPayload(CMutableTransaction& tx, const T& payload) +{ + CDataStream ds(SER_NETWORK, PROTOCOL_VERSION); + ds << payload; + tx.vExtraPayload.assign(ds.begin(), ds.end()); +} + uint256 CalcTxInputsHash(const CTransaction& tx); #endif//DASH_SPECIALTX_H From 01e07d892db8c50701c04a2a2a97071b8ddffab3 Mon Sep 17 00:00:00 2001 From: Alexander Block Date: Fri, 23 Feb 2018 11:37:14 +0100 Subject: [PATCH 056/282] Support version 3 transaction serialization in mininode.py --- qa/rpc-tests/test_framework/mininode.py | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/qa/rpc-tests/test_framework/mininode.py b/qa/rpc-tests/test_framework/mininode.py index 2458b856f75d..b34d5f2d10ca 100755 --- a/qa/rpc-tests/test_framework/mininode.py +++ b/qa/rpc-tests/test_framework/mininode.py @@ -357,33 +357,44 @@ class CTransaction(object): def __init__(self, tx=None): if tx is None: self.nVersion = 1 + self.nType = 0 self.vin = [] self.vout = [] self.nLockTime = 0 + self.vExtraPayload = None self.sha256 = None self.hash = None else: self.nVersion = tx.nVersion + self.nType = tx.nType self.vin = copy.deepcopy(tx.vin) self.vout = copy.deepcopy(tx.vout) self.nLockTime = tx.nLockTime + self.vExtraPayload = tx.vExtraPayload self.sha256 = tx.sha256 self.hash = tx.hash def deserialize(self, f): - self.nVersion = struct.unpack("> 16) & 0xffff self.vin = deser_vector(f, CTxIn) self.vout = deser_vector(f, CTxOut) self.nLockTime = struct.unpack(" Date: Wed, 28 Feb 2018 10:10:36 +0100 Subject: [PATCH 057/282] Account for extraPayload when calculating fees in FundTransaction --- src/wallet/wallet.cpp | 13 +++++++++++-- src/wallet/wallet.h | 2 +- 2 files changed, 12 insertions(+), 3 deletions(-) diff --git a/src/wallet/wallet.cpp b/src/wallet/wallet.cpp index f62db6544812..0f88a7b8bb5f 100644 --- a/src/wallet/wallet.cpp +++ b/src/wallet/wallet.cpp @@ -2962,9 +2962,13 @@ bool CWallet::FundTransaction(CMutableTransaction& tx, CAmount& nFeeRet, bool ov BOOST_FOREACH(const CTxIn& txin, tx.vin) coinControl.Select(txin.prevout); + int nExtraPayloadSize = 0; + if (tx.nVersion >= 3 && tx.nType != TRANSACTION_NORMAL) + nExtraPayloadSize = (int)tx.vExtraPayload.size(); + CReserveKey reservekey(this); CWalletTx wtx; - if (!CreateTransaction(vecSend, wtx, reservekey, nFeeRet, nChangePosInOut, strFailReason, &coinControl, false)) + if (!CreateTransaction(vecSend, wtx, reservekey, nFeeRet, nChangePosInOut, strFailReason, &coinControl, false, ALL_COINS, false, nExtraPayloadSize)) return false; if (nChangePosInOut != -1) @@ -3402,7 +3406,7 @@ bool CWallet::ConvertList(std::vector vecTxIn, std::vector& vecA } bool CWallet::CreateTransaction(const std::vector& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, CAmount& nFeeRet, - int& nChangePosInOut, std::string& strFailReason, const CCoinControl* coinControl, bool sign, AvailableCoinsType nCoinType, bool fUseInstantSend) + int& nChangePosInOut, std::string& strFailReason, const CCoinControl* coinControl, bool sign, AvailableCoinsType nCoinType, bool fUseInstantSend, int nExtraPayloadSize) { CAmount nFeePay = fUseInstantSend ? CTxLockRequest().GetMinFee() : 0; @@ -3704,6 +3708,11 @@ bool CWallet::CreateTransaction(const std::vector& vecSend, CWalletT unsigned int nBytes = ::GetSerializeSize(txNew, SER_NETWORK, PROTOCOL_VERSION); + if (nExtraPayloadSize != 0) { + // account for extra payload in fee calculation + nBytes += GetSizeOfCompactSize(nExtraPayloadSize) + nExtraPayloadSize; + } + if (nBytes > MAX_STANDARD_TX_SIZE) { // Do not create oversized transactions (bad-txns-oversize). strFailReason = _("Transaction too large"); diff --git a/src/wallet/wallet.h b/src/wallet/wallet.h index 39c2e3df548f..eb282f4be6ef 100644 --- a/src/wallet/wallet.h +++ b/src/wallet/wallet.h @@ -936,7 +936,7 @@ class CWallet : public CCryptoKeyStore, public CValidationInterface * @note passing nChangePosInOut as -1 will result in setting a random position */ bool CreateTransaction(const std::vector& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, CAmount& nFeeRet, int& nChangePosInOut, - std::string& strFailReason, const CCoinControl *coinControl = NULL, bool sign = true, AvailableCoinsType nCoinType=ALL_COINS, bool fUseInstantSend=false); + std::string& strFailReason, const CCoinControl *coinControl = NULL, bool sign = true, AvailableCoinsType nCoinType=ALL_COINS, bool fUseInstantSend=false, int nExtraPayloadSize = 0); bool CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey, CConnman* connman, CValidationState& state, const std::string& strCommand="tx"); bool CreateCollateralTransaction(CMutableTransaction& txCollateral, std::string& strReason); From 122a0cf6a8565c8db55514f4ab9cf9f5efabecc7 Mon Sep 17 00:00:00 2001 From: Alexander Block Date: Tue, 28 Aug 2018 15:45:29 +0200 Subject: [PATCH 058/282] Add extraPayloadSize/extraPayload fields to RPC help --- src/rpc/rawtransaction.cpp | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/rpc/rawtransaction.cpp b/src/rpc/rawtransaction.cpp index 220a8eea1e88..ea5b589f3c9c 100644 --- a/src/rpc/rawtransaction.cpp +++ b/src/rpc/rawtransaction.cpp @@ -203,6 +203,8 @@ UniValue getrawtransaction(const JSONRPCRequest& request) " }\n" " ,...\n" " ],\n" + " \"extraPayloadSize\" : n (numeric) Size of DIP2 extra payload. Only present if it's a special TX\n" + " \"extraPayload\" : \"hex\" (string) Hex encoded DIP2 extra payload data. Only present if it's a special TX\n" " \"blockhash\" : \"hash\", (string) the block hash\n" " \"confirmations\" : n, (numeric) The confirmations\n" " \"time\" : ttt, (numeric) The transaction time in seconds since epoch (Jan 1 1970 GMT)\n" @@ -536,6 +538,8 @@ UniValue decoderawtransaction(const JSONRPCRequest& request) " }\n" " ,...\n" " ],\n" + " \"extraPayloadSize\" : n (numeric) Size of DIP2 extra payload. Only present if it's a special TX\n" + " \"extraPayload\" : \"hex\" (string) Hex encoded DIP2 extra payload data. Only present if it's a special TX\n" "}\n" "\nExamples:\n" From e0d6722bc1092a08b7ca12f15dfc6e77f3e7c44d Mon Sep 17 00:00:00 2001 From: UdjinM6 Date: Wed, 29 Aug 2018 13:02:54 +0300 Subject: [PATCH 059/282] Fix sync in regtest (again) (#2241) Should only call SwitchToNextAsset() while being in specific state and not on every tick --- src/masternode-sync.cpp | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/masternode-sync.cpp b/src/masternode-sync.cpp index be5c475e590f..81bfc163ef7d 100644 --- a/src/masternode-sync.cpp +++ b/src/masternode-sync.cpp @@ -187,8 +187,10 @@ void CMasternodeSync::ProcessTick(CConnman& connman) { if (nRequestedMasternodeAssets == MASTERNODE_SYNC_WAITING) { connman.PushMessage(pnode, msgMaker.Make(NetMsgType::GETSPORKS)); //get current network sporks + SwitchToNextAsset(connman); } else if (nRequestedMasternodeAssets == MASTERNODE_SYNC_LIST) { mnodeman.DsegUpdate(pnode, connman); + SwitchToNextAsset(connman); } else if (nRequestedMasternodeAssets == MASTERNODE_SYNC_MNW) { //sync payment votes if(pnode->nVersion == 70208) { @@ -196,10 +198,11 @@ void CMasternodeSync::ProcessTick(CConnman& connman) } else { connman.PushMessage(pnode, msgMaker.Make(NetMsgType::MASTERNODEPAYMENTSYNC)); //sync payment votes } + SwitchToNextAsset(connman); } else if (nRequestedMasternodeAssets == MASTERNODE_SYNC_GOVERNANCE) { SendGovernanceSyncRequest(pnode, connman); + SwitchToNextAsset(connman); } - SwitchToNextAsset(connman); connman.ReleaseNodeVector(vNodesCopy); return; } From cb5b624e03a0debc34c17cbb69425af025612f11 Mon Sep 17 00:00:00 2001 From: Alexander Block Date: Wed, 29 Aug 2018 12:03:18 +0200 Subject: [PATCH 060/282] Fix caching issues in Jenkins --- Jenkinsfile | 99 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 99 insertions(+) create mode 100644 Jenkinsfile diff --git a/Jenkinsfile b/Jenkinsfile new file mode 100644 index 000000000000..71d7db3adbc3 --- /dev/null +++ b/Jenkinsfile @@ -0,0 +1,99 @@ +// This Jenkinsfile will build a builder image and then run the actual build and tests inside this image +// It's very important to not execute any scripts outside of the builder container, as it's our protection against +// external developers bringing in harmful code into Jenkins. +// Jenkins will only run the build if this Jenkinsfile was not modified in an external pull request. Only branches +// which are part of the Absolute repo will allow modification to the Jenkinsfile. + +def targets = [ + 'win32', + 'win64', + 'linux32', + 'linux64', + 'linux64_nowallet', + 'linux64_release', + 'mac', +] + +def tasks = [:] +for(int i = 0; i < targets.size(); i++) { + def target = targets[i] + + tasks["${target}"] = { + node { + def BUILD_NUMBER = sh(returnStdout: true, script: 'echo $BUILD_NUMBER').trim() + def BRANCH_NAME = sh(returnStdout: true, script: 'echo $BRANCH_NAME').trim() + def UID = sh(returnStdout: true, script: 'id -u').trim() + def HOME = sh(returnStdout: true, script: 'echo $HOME').trim() + def pwd = sh(returnStdout: true, script: 'pwd').trim() + + checkout scm + + def env = [ + "BUILD_TARGET=${target}", + "PULL_REQUEST=false", + "JOB_NUMBER=${BUILD_NUMBER}", + ] + withEnv(env) { + def builderImageName="absolute-builder-${target}" + + def builderImage + stage("${target}/builder-image") { + builderImage = docker.build("${builderImageName}", "--build-arg BUILD_TARGET=${target} ci -f ci/Dockerfile.builder") + } + + builderImage.inside("-t") { + // copy source into fixed path + // we must build under the same path everytime as otherwise caches won't work properly + sh "cp -ra ${pwd}/. /absolute-src/" + + // restore cache + def hasCache = false + try { + copyArtifacts(projectName: "absolute/${BRANCH_NAME}", optional: true, selector: lastSuccessful(), filter: "ci-cache-${target}.tar.gz") + } catch (Exception e) { + } + if (fileExists("ci-cache-${target}.tar.gz")) { + hasCache = true + echo "Using cache from absolute/${BRANCH_NAME}" + } else { + try { + copyArtifacts(projectName: 'absolute/develop', optional: true, selector: lastSuccessful(), filter: "ci-cache-${target}.tar.gz"); + } catch (Exception e) { + } + if (fileExists("ci-cache-${target}.tar.gz")) { + hasCache = true + echo "Using cache from absolute/develop" + } + } + + if (hasCache) { + sh "cd /absolute-src && tar xzf ${pwd}/ci-cache-${target}.tar.gz" + } else { + sh "mkdir -p /absolute-src/ci-cache-${target}" + } + + stage("${target}/depends") { + sh 'cd /absolute-src && ./ci/build_depends.sh' + } + stage("${target}/build") { + sh 'cd /absolute-src && ./ci/build_src.sh' + } + stage("${target}/test") { + sh 'cd /absolute-src && ./ci/test_unittests.sh' + } + stage("${target}/test") { + sh 'cd /absolute-src && ./ci/test_integrationtests.sh' + } + + // archive cache and copy it into the jenkins workspace + sh "cd /absolute-src && tar czfv ci-cache-${target}.tar.gz ci-cache-${target} && cp ci-cache-${target}.tar.gz ${pwd}/" + } + + // upload cache + archiveArtifacts artifacts: "ci-cache-${target}.tar.gz", fingerprint: true + } + } + } +} + +parallel tasks From efac117e04f3e453e5f506cad909897c1fa7bb75 Mon Sep 17 00:00:00 2001 From: gladcow Date: Wed, 29 Aug 2018 14:36:35 +0300 Subject: [PATCH 061/282] Refactor `masternode` and `gobject` RPCs * Support help for masternode rpc call subcommands * Support help for gobject rpc call subcommands * squash ifs for conditions to show help * remove code duplication for masternode list and masternodelist help calls --- src/rpc/governance.cpp | 1285 +++++++++++++++++++++++----------------- src/rpc/masternode.cpp | 890 ++++++++++++++++++---------- 2 files changed, 1337 insertions(+), 838 deletions(-) diff --git a/src/rpc/governance.cpp b/src/rpc/governance.cpp index 31efd08726ff..df347136fafb 100644 --- a/src/rpc/governance.cpp +++ b/src/rpc/governance.cpp @@ -27,358 +27,449 @@ bool EnsureWalletIsAvailable(bool avoidException); -UniValue gobject(const JSONRPCRequest& request) +void gobject_count_help() { - std::string strCommand; - if (request.params.size() >= 1) - strCommand = request.params[0].get_str(); - - if (request.fHelp || - ( -#ifdef ENABLE_WALLET - strCommand != "prepare" && -#endif // ENABLE_WALLET - strCommand != "vote-many" && strCommand != "vote-conf" && strCommand != "vote-alias" && strCommand != "submit" && strCommand != "count" && - strCommand != "deserialize" && strCommand != "get" && strCommand != "getvotes" && strCommand != "getcurrentvotes" && strCommand != "list" && strCommand != "diff" && - strCommand != "check" )) - throw std::runtime_error( - "gobject \"command\"...\n" - "Manage governance objects\n" - "\nAvailable commands:\n" - " check - Validate governance object data (proposal only)\n" -#ifdef ENABLE_WALLET - " prepare - Prepare governance object by signing and creating tx\n" -#endif // ENABLE_WALLET - " submit - Submit governance object to network\n" - " deserialize - Deserialize governance object from hex string to JSON\n" - " count - Count governance objects and votes (additional param: 'json' or 'all', default: 'json')\n" - " get - Get governance object by hash\n" - " getvotes - Get all votes for a governance object hash (including old votes)\n" - " getcurrentvotes - Get only current (tallying) votes for a governance object hash (does not include old votes)\n" - " list - List governance objects (can be filtered by signal and/or object type)\n" - " diff - List differences since last diff\n" - " vote-alias - Vote on a governance object by masternode alias (using masternode.conf setup)\n" - " vote-conf - Vote on a governance object by masternode configured in absolute.conf\n" - " vote-many - Vote on a governance object by all masternodes (using masternode.conf setup)\n" + throw std::runtime_error( + "gobject count (\"mode\")\n" + "Count governance objects and votes\n" + "\nArguments:\n" + "1. \"mode\" (string, optional, default: \"json\") Output format: json (\"json\") or string in free form (\"all\")\n" ); +} +UniValue gobject_count(const JSONRPCRequest& request) +{ + if (request.fHelp || request.params.size() > 2) + gobject_count_help(); - if(strCommand == "count") { - std::string strMode{"json"}; + std::string strMode{"json"}; - if (request.params.size() == 2) { - strMode = request.params[1].get_str(); - } + if (request.params.size() == 2) { + strMode = request.params[1].get_str(); + } - if (request.params.size() > 2 || (strMode != "json" && strMode != "all")) { - throw JSONRPCError(RPC_INVALID_PARAMETER, "Correct usage is 'gobject count ( \"json\"|\"all\" )'"); - } + if (strMode != "json" && strMode != "all") + gobject_count_help(); - return strMode == "json" ? governance.ToJson() : governance.ToString(); - } - /* - ------ Example Governance Item ------ + return strMode == "json" ? governance.ToJson() : governance.ToString(); +} - gobject submit 6e622bb41bad1fb18e7f23ae96770aeb33129e18bd9efe790522488e580a0a03 0 1 1464292854 "beer-reimbursement" 5b5b22636f6e7472616374222c207b2270726f6a6563745f6e616d65223a20225c22626565722d7265696d62757273656d656e745c22222c20227061796d656e745f61646472657373223a20225c225879324c4b4a4a64655178657948726e34744744514238626a6876464564615576375c22222c2022656e645f64617465223a202231343936333030343030222c20226465736372697074696f6e5f75726c223a20225c227777772e646173687768616c652e6f72672f702f626565722d7265696d62757273656d656e745c22222c2022636f6e74726163745f75726c223a20225c22626565722d7265696d62757273656d656e742e636f6d2f3030312e7064665c22222c20227061796d656e745f616d6f756e74223a20223233342e323334323232222c2022676f7665726e616e63655f6f626a6563745f6964223a2037342c202273746172745f64617465223a202231343833323534303030227d5d5d1 - */ +void gobject_deserialize_help() +{ + throw std::runtime_error( + "gobject deserialize \"hex_data\"\n" + "Deserialize governance object from hex string to JSON\n" + "\nArguments:\n" + "1. \"hex_data\" (string, required) data in hex string form\n" + ); +} - // DEBUG : TEST DESERIALIZATION OF GOVERNANCE META DATA - if(strCommand == "deserialize") - { - if (request.params.size() != 2) { - throw JSONRPCError(RPC_INVALID_PARAMETER, "Correct usage is 'gobject deserialize '"); - } +UniValue gobject_deserialize(const JSONRPCRequest& request) +{ + if (request.fHelp || request.params.size() != 2) + gobject_deserialize_help(); - std::string strHex = request.params[1].get_str(); + std::string strHex = request.params[1].get_str(); - std::vector v = ParseHex(strHex); - std::string s(v.begin(), v.end()); + std::vector v = ParseHex(strHex); + std::string s(v.begin(), v.end()); - UniValue u(UniValue::VOBJ); - u.read(s); + UniValue u(UniValue::VOBJ); + u.read(s); - return u.write().c_str(); - } + return u.write().c_str(); +} - // VALIDATE A GOVERNANCE OBJECT PRIOR TO SUBMISSION - if(strCommand == "check") - { - if (request.params.size() != 2) { - throw JSONRPCError(RPC_INVALID_PARAMETER, "Correct usage is 'gobject check '"); - } +void gobject_check_help() +{ + throw std::runtime_error( + "gobject check \"hex_data\"\n" + "Validate governance object data (proposal only)\n" + "\nArguments:\n" + "1. \"hex_data\" (string, required) data in hex string form\n" + ); +} - // ASSEMBLE NEW GOVERNANCE OBJECT FROM USER PARAMETERS +UniValue gobject_check(const JSONRPCRequest& request) +{ + if (request.fHelp || request.params.size() != 2) + gobject_check_help(); - uint256 hashParent; + // ASSEMBLE NEW GOVERNANCE OBJECT FROM USER PARAMETERS - int nRevision = 1; + uint256 hashParent; - int64_t nTime = GetAdjustedTime(); - std::string strDataHex = request.params[1].get_str(); + int nRevision = 1; - CGovernanceObject govobj(hashParent, nRevision, nTime, uint256(), strDataHex); + int64_t nTime = GetAdjustedTime(); + std::string strDataHex = request.params[1].get_str(); - if(govobj.GetObjectType() == GOVERNANCE_OBJECT_PROPOSAL) { - CProposalValidator validator(strDataHex); - if(!validator.Validate()) { - throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid proposal data, error messages:" + validator.GetErrorMessages()); - } - } - else { - throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid object type, only proposals can be validated"); + CGovernanceObject govobj(hashParent, nRevision, nTime, uint256(), strDataHex); + + if(govobj.GetObjectType() == GOVERNANCE_OBJECT_PROPOSAL) { + CProposalValidator validator(strDataHex); + if(!validator.Validate()) { + throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid proposal data, error messages:" + validator.GetErrorMessages()); } + } + else { + throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid object type, only proposals can be validated"); + } - UniValue objResult(UniValue::VOBJ); + UniValue objResult(UniValue::VOBJ); - objResult.push_back(Pair("Object status", "OK")); + objResult.push_back(Pair("Object status", "OK")); - return objResult; - } + return objResult; +} #ifdef ENABLE_WALLET - // PREPARE THE GOVERNANCE OBJECT BY CREATING A COLLATERAL TRANSACTION - if(strCommand == "prepare") - { - if (!EnsureWalletIsAvailable(request.fHelp)) - return NullUniValue; - - if (request.params.size() != 5) { - throw JSONRPCError(RPC_INVALID_PARAMETER, "Correct usage is 'gobject prepare