Boolberry support

master
lucas 2014-06-03 21:18:55 +01:00
parent f90249d57b
commit f05427a7ad
17 changed files with 1869 additions and 5 deletions

View File

@ -19,6 +19,7 @@
"shavite3.c",
"cryptonight.c",
"x13.c",
"boolberry.cc",
"sha3/sph_hefty1.c",
"sha3/sph_fugue.c",
"sha3/aes_helper.c",
@ -41,8 +42,15 @@
"crypto/c_jh.c",
"crypto/c_skein.c",
"crypto/hash.c",
"crypto/aesb.c"
]
"crypto/aesb.c",
"crypto/wild_keccak.cpp"
],
"include_dirs": [
"crypto",
],
"cflags_cc": [
"-std=c++0x"
],
}
]
}

11
boolberry.cc 100644
View File

@ -0,0 +1,11 @@
#include "boolberry.h"
#include "crypto/cryptonote_core/cryptonote_format_utils.h"
#include <iostream>
void boolberry_hash(const char* input, uint32_t input_len, const char* scratchpad, uint64_t spad_length, char* output, uint64_t height) {
crypto::hash* spad = (crypto::hash*) scratchpad;
cryptonote::get_blob_longhash_bb(std::string(input, input_len), *((crypto::hash*)output), height, [&](uint64_t index) -> crypto::hash& {
return spad[index%(spad_length / HASH_SIZE)];
});
}

6
boolberry.h 100644
View File

@ -0,0 +1,6 @@
#pragma once
#include <stdint.h>
#include <string>
void boolberry_hash(const char* input, uint32_t input_len, const char* scratchpad, uint64_t spad_length, char* output, uint64_t height);

View File

@ -110,7 +110,7 @@ HashReturn jh_hash(int hashbitlen, const BitSequence *data,DataLength databitlen
/*swapping bits 32i||32i+1||......||32i+15 with bits 32i+16||32i+17||......||32i+31 of 64-bit x*/
#define SWAP16(x) (x) = ((((x) & 0x0000ffff0000ffffULL) << 16) | (((x) & 0xffff0000ffff0000ULL) >> 16));
/*swapping bits 64i||64i+1||......||64i+31 with bits 64i+32||64i+33||......||64i+63 of 64-bit x*/
#define SWAP32(x) (x) = (((x) << 32) | ((x) >> 32));
#define SWAP32_JH(x) (x) = (((x) << 32) | ((x) >> 32));
/*The MDS transform*/
#define L(m0,m1,m2,m3,m4,m5,m6,m7) \
@ -194,7 +194,7 @@ static void E8(hashState *state)
for (i = 0; i < 2; i++) {
SS(state->x[0][i],state->x[2][i],state->x[4][i],state->x[6][i],state->x[1][i],state->x[3][i],state->x[5][i],state->x[7][i],((uint64*)E8_bitslice_roundconstant[roundnumber+5])[i],((uint64*)E8_bitslice_roundconstant[roundnumber+5])[i+2] );
L(state->x[0][i],state->x[2][i],state->x[4][i],state->x[6][i],state->x[1][i],state->x[3][i],state->x[5][i],state->x[7][i]);
SWAP32(state->x[1][i]); SWAP32(state->x[3][i]); SWAP32(state->x[5][i]); SWAP32(state->x[7][i]);
SWAP32_JH(state->x[1][i]); SWAP32_JH(state->x[3][i]); SWAP32_JH(state->x[5][i]); SWAP32_JH(state->x[7][i]);
}
/*round 7*roundnumber+6: Sbox and MDS layers*/

186
crypto/crypto.h 100644
View File

@ -0,0 +1,186 @@
// Copyright (c) 2012-2013 The Cryptonote developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#pragma once
#include <cstddef>
#include <mutex>
#include <vector>
#include "common/pod-class.h"
#include "generic-ops.h"
#include "hash.h"
namespace crypto {
extern "C" {
#include "random.h"
}
extern std::mutex random_lock;
#pragma pack(push, 1)
POD_CLASS ec_point {
char data[32];
};
POD_CLASS ec_scalar {
char data[32];
};
POD_CLASS public_key: ec_point {
friend class crypto_ops;
};
POD_CLASS secret_key: ec_scalar {
friend class crypto_ops;
};
POD_CLASS key_derivation: ec_point {
friend class crypto_ops;
};
POD_CLASS key_image: ec_point {
friend class crypto_ops;
};
POD_CLASS signature {
ec_scalar c, r;
friend class crypto_ops;
};
#pragma pack(pop)
static_assert(sizeof(ec_point) == 32 && sizeof(ec_scalar) == 32 &&
sizeof(public_key) == 32 && sizeof(secret_key) == 32 &&
sizeof(key_derivation) == 32 && sizeof(key_image) == 32 &&
sizeof(signature) == 64, "Invalid structure size");
class crypto_ops {
crypto_ops();
crypto_ops(const crypto_ops &);
void operator=(const crypto_ops &);
~crypto_ops();
static void generate_keys(public_key &, secret_key &);
friend void generate_keys(public_key &, secret_key &);
static bool check_key(const public_key &);
friend bool check_key(const public_key &);
static bool secret_key_to_public_key(const secret_key &, public_key &);
friend bool secret_key_to_public_key(const secret_key &, public_key &);
static bool generate_key_derivation(const public_key &, const secret_key &, key_derivation &);
friend bool generate_key_derivation(const public_key &, const secret_key &, key_derivation &);
static bool derive_public_key(const key_derivation &, std::size_t, const public_key &, public_key &);
friend bool derive_public_key(const key_derivation &, std::size_t, const public_key &, public_key &);
static void derive_secret_key(const key_derivation &, std::size_t, const secret_key &, secret_key &);
friend void derive_secret_key(const key_derivation &, std::size_t, const secret_key &, secret_key &);
static void generate_signature(const hash &, const public_key &, const secret_key &, signature &);
friend void generate_signature(const hash &, const public_key &, const secret_key &, signature &);
static bool check_signature(const hash &, const public_key &, const signature &);
friend bool check_signature(const hash &, const public_key &, const signature &);
static void generate_key_image(const public_key &, const secret_key &, key_image &);
friend void generate_key_image(const public_key &, const secret_key &, key_image &);
static void generate_ring_signature(const hash &, const key_image &,
const public_key *const *, std::size_t, const secret_key &, std::size_t, signature *);
friend void generate_ring_signature(const hash &, const key_image &,
const public_key *const *, std::size_t, const secret_key &, std::size_t, signature *);
static bool check_ring_signature(const hash &, const key_image &,
const public_key *const *, std::size_t, const signature *);
friend bool check_ring_signature(const hash &, const key_image &,
const public_key *const *, std::size_t, const signature *);
};
/* Generate a value filled with random bytes.
*/
template<typename T>
typename std::enable_if<std::is_pod<T>::value, T>::type rand() {
typename std::remove_cv<T>::type res;
std::lock_guard<std::mutex> lock(random_lock);
generate_random_bytes(sizeof(T), &res);
return res;
}
/* Generate a new key pair
*/
inline void generate_keys(public_key &pub, secret_key &sec) {
crypto_ops::generate_keys(pub, sec);
}
/* Check a public key. Returns true if it is valid, false otherwise.
*/
inline bool check_key(const public_key &key) {
return crypto_ops::check_key(key);
}
/* Checks a private key and computes the corresponding public key.
*/
inline bool secret_key_to_public_key(const secret_key &sec, public_key &pub) {
return crypto_ops::secret_key_to_public_key(sec, pub);
}
/* To generate an ephemeral key used to send money to:
* * The sender generates a new key pair, which becomes the transaction key. The public transaction key is included in "extra" field.
* * Both the sender and the receiver generate key derivation from the transaction key, the receivers' "view" key and the output index.
* * The sender uses key derivation and the receivers' "spend" key to derive an ephemeral public key.
* * The receiver can either derive the public key (to check that the transaction is addressed to him) or the private key (to spend the money).
*/
inline bool generate_key_derivation(const public_key &key1, const secret_key &key2, key_derivation &derivation) {
return crypto_ops::generate_key_derivation(key1, key2, derivation);
}
inline bool derive_public_key(const key_derivation &derivation, std::size_t output_index,
const public_key &base, public_key &derived_key) {
return crypto_ops::derive_public_key(derivation, output_index, base, derived_key);
}
inline void derive_secret_key(const key_derivation &derivation, std::size_t output_index,
const secret_key &base, secret_key &derived_key) {
crypto_ops::derive_secret_key(derivation, output_index, base, derived_key);
}
/* Generation and checking of a standard signature.
*/
inline void generate_signature(const hash &prefix_hash, const public_key &pub, const secret_key &sec, signature &sig) {
crypto_ops::generate_signature(prefix_hash, pub, sec, sig);
}
inline bool check_signature(const hash &prefix_hash, const public_key &pub, const signature &sig) {
return crypto_ops::check_signature(prefix_hash, pub, sig);
}
/* To send money to a key:
* * The sender generates an ephemeral key and includes it in transaction output.
* * To spend the money, the receiver generates a key image from it.
* * Then he selects a bunch of outputs, including the one he spends, and uses them to generate a ring signature.
* To check the signature, it is necessary to collect all the keys that were used to generate it. To detect double spends, it is necessary to check that each key image is used at most once.
*/
inline void generate_key_image(const public_key &pub, const secret_key &sec, key_image &image) {
crypto_ops::generate_key_image(pub, sec, image);
}
inline void generate_ring_signature(const hash &prefix_hash, const key_image &image,
const public_key *const *pubs, std::size_t pubs_count,
const secret_key &sec, std::size_t sec_index,
signature *sig) {
crypto_ops::generate_ring_signature(prefix_hash, image, pubs, pubs_count, sec, sec_index, sig);
}
inline bool check_ring_signature(const hash &prefix_hash, const key_image &image,
const public_key *const *pubs, std::size_t pubs_count,
const signature *sig) {
return crypto_ops::check_ring_signature(prefix_hash, image, pubs, pubs_count, sig);
}
/* Variants with vector<const public_key *> parameters.
*/
inline void generate_ring_signature(const hash &prefix_hash, const key_image &image,
const std::vector<const public_key *> &pubs,
const secret_key &sec, std::size_t sec_index,
signature *sig) {
generate_ring_signature(prefix_hash, image, pubs.data(), pubs.size(), sec, sec_index, sig);
}
inline bool check_ring_signature(const hash &prefix_hash, const key_image &image,
const std::vector<const public_key *> &pubs,
const signature *sig) {
return check_ring_signature(prefix_hash, image, pubs.data(), pubs.size(), sig);
}
}
CRYPTO_MAKE_COMPARABLE(public_key)
CRYPTO_MAKE_HASHABLE(key_image)
CRYPTO_MAKE_COMPARABLE(signature)

View File

@ -0,0 +1,50 @@
// Copyright (c) 2012-2013 The Cryptonote developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <boost/archive/binary_oarchive.hpp>
#include <boost/archive/binary_iarchive.hpp>
#include <fstream>
#include "include_base_utils.h"
#include "account.h"
#include "warnings.h"
#include "crypto/crypto.h"
#include "cryptonote_core/cryptonote_basic_impl.h"
#include "cryptonote_core/cryptonote_format_utils.h"
using namespace std;
DISABLE_VS_WARNINGS(4244 4345)
namespace cryptonote
{
//-----------------------------------------------------------------
account_base::account_base()
{
set_null();
}
//-----------------------------------------------------------------
void account_base::set_null()
{
m_keys = account_keys();
}
//-----------------------------------------------------------------
void account_base::generate()
{
generate_keys(m_keys.m_account_address.m_spend_public_key, m_keys.m_spend_secret_key);
generate_keys(m_keys.m_account_address.m_view_public_key, m_keys.m_view_secret_key);
m_creation_timestamp = time(NULL);
}
//-----------------------------------------------------------------
const account_keys& account_base::get_keys() const
{
return m_keys;
}
//-----------------------------------------------------------------
std::string account_base::get_public_address_str()
{
//TODO: change this code into base 58
return get_account_address_as_str(m_keys.m_account_address);
}
//-----------------------------------------------------------------
}

View File

@ -0,0 +1,61 @@
// Copyright (c) 2012-2013 The Cryptonote developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#pragma once
#include "cryptonote_core/cryptonote_basic.h"
#include "crypto/crypto.h"
#include "serialization/keyvalue_serialization.h"
namespace cryptonote
{
struct account_keys
{
account_public_address m_account_address;
crypto::secret_key m_spend_secret_key;
crypto::secret_key m_view_secret_key;
BEGIN_KV_SERIALIZE_MAP()
KV_SERIALIZE(m_account_address)
KV_SERIALIZE_VAL_POD_AS_BLOB_FORCE(m_spend_secret_key)
KV_SERIALIZE_VAL_POD_AS_BLOB_FORCE(m_view_secret_key)
END_KV_SERIALIZE_MAP()
};
/************************************************************************/
/* */
/************************************************************************/
class account_base
{
public:
account_base();
void generate();
const account_keys& get_keys() const;
std::string get_public_address_str();
uint64_t get_createtime() const { return m_creation_timestamp; }
void set_createtime(uint64_t val) { m_creation_timestamp = val; }
bool load(const std::string& file_path);
bool store(const std::string& file_path);
template <class t_archive>
inline void serialize(t_archive &a, const unsigned int /*ver*/)
{
a & m_keys;
a & m_creation_timestamp;
}
BEGIN_KV_SERIALIZE_MAP()
KV_SERIALIZE(m_keys)
KV_SERIALIZE(m_creation_timestamp)
END_KV_SERIALIZE_MAP()
private:
void set_null();
account_keys m_keys;
uint64_t m_creation_timestamp;
};
}

View File

@ -0,0 +1,186 @@
// Copyright (c) 2012-2013 The Cryptonote developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "include_base_utils.h"
using namespace epee;
#include "cryptonote_basic_impl.h"
#include "string_tools.h"
#include "serialization/binary_utils.h"
#include "serialization/vector.h"
#include "cryptonote_format_utils.h"
#include "cryptonote_config.h"
#include "misc_language.h"
#include "common/base58.h"
#include "crypto/hash.h"
#include "common/int-util.h"
namespace cryptonote {
/************************************************************************/
/* Cryptonote helper functions */
/************************************************************************/
//-----------------------------------------------------------------------------------------------
size_t get_max_block_size()
{
return CRYPTONOTE_MAX_BLOCK_SIZE;
}
//-----------------------------------------------------------------------------------------------
size_t get_max_tx_size()
{
return CRYPTONOTE_MAX_TX_SIZE;
}
//-----------------------------------------------------------------------------------------------
bool get_block_reward(size_t median_size, size_t current_block_size, uint64_t already_generated_coins, uint64_t &reward) {
uint64_t base_reward = (MONEY_SUPPLY - already_generated_coins) >> EMISSION_SPEED_FACTOR;
//make it soft
if (median_size < CRYPTONOTE_BLOCK_GRANTED_FULL_REWARD_ZONE) {
median_size = CRYPTONOTE_BLOCK_GRANTED_FULL_REWARD_ZONE;
}
if (current_block_size <= median_size) {
reward = base_reward;
return true;
}
if(current_block_size > 2 * median_size) {
LOG_PRINT_L4("Block cumulative size is too big: " << current_block_size << ", expected less than " << 2 * median_size);
return false;
}
assert(median_size < std::numeric_limits<uint32_t>::max());
assert(current_block_size < std::numeric_limits<uint32_t>::max());
uint64_t product_hi;
uint64_t product_lo = mul128(base_reward, current_block_size * (2 * median_size - current_block_size), &product_hi);
uint64_t reward_hi;
uint64_t reward_lo;
div128_32(product_hi, product_lo, static_cast<uint32_t>(median_size), &reward_hi, &reward_lo);
div128_32(reward_hi, reward_lo, static_cast<uint32_t>(median_size), &reward_hi, &reward_lo);
assert(0 == reward_hi);
assert(reward_lo < base_reward);
reward = reward_lo;
return true;
}
//------------------------------------------------------------------------------------
uint8_t get_account_address_checksum(const public_address_outer_blob& bl)
{
const unsigned char* pbuf = reinterpret_cast<const unsigned char*>(&bl);
uint8_t summ = 0;
for(size_t i = 0; i!= sizeof(public_address_outer_blob)-1; i++)
summ += pbuf[i];
return summ;
}
//-----------------------------------------------------------------------
std::string get_account_address_as_str(const account_public_address& adr)
{
return tools::base58::encode_addr(CRYPTONOTE_PUBLIC_ADDRESS_BASE58_PREFIX, t_serializable_object_to_blob(adr));
}
//-----------------------------------------------------------------------
bool is_coinbase(const transaction& tx)
{
if(tx.vin.size() != 1)
return false;
if(tx.vin[0].type() != typeid(txin_gen))
return false;
return true;
}
//-----------------------------------------------------------------------
bool get_account_address_from_str(account_public_address& adr, const std::string& str)
{
if (2 * sizeof(public_address_outer_blob) != str.size())
{
blobdata data;
uint64_t prefix;
if (!tools::base58::decode_addr(str, prefix, data))
{
LOG_PRINT_L1("Invalid address format");
return false;
}
if (CRYPTONOTE_PUBLIC_ADDRESS_BASE58_PREFIX != prefix)
{
LOG_PRINT_L1("Wrong address prefix: " << prefix << ", expected " << CRYPTONOTE_PUBLIC_ADDRESS_BASE58_PREFIX);
return false;
}
if (!::serialization::parse_binary(data, adr))
{
LOG_PRINT_L1("Account public address keys can't be parsed");
return false;
}
if (!crypto::check_key(adr.m_spend_public_key) || !crypto::check_key(adr.m_view_public_key))
{
LOG_PRINT_L1("Failed to validate address keys");
return false;
}
}
else
{
// Old address format
std::string buff;
if(!string_tools::parse_hexstr_to_binbuff(str, buff))
return false;
if(buff.size()!=sizeof(public_address_outer_blob))
{
LOG_PRINT_L1("Wrong public address size: " << buff.size() << ", expected size: " << sizeof(public_address_outer_blob));
return false;
}
public_address_outer_blob blob = *reinterpret_cast<const public_address_outer_blob*>(buff.data());
if(blob.m_ver > CRYPTONOTE_PUBLIC_ADDRESS_TEXTBLOB_VER)
{
LOG_PRINT_L1("Unknown version of public address: " << blob.m_ver << ", expected " << CRYPTONOTE_PUBLIC_ADDRESS_TEXTBLOB_VER);
return false;
}
if(blob.check_sum != get_account_address_checksum(blob))
{
LOG_PRINT_L1("Wrong public address checksum");
return false;
}
//we success
adr = blob.m_address;
}
return true;
}
bool operator ==(const cryptonote::transaction& a, const cryptonote::transaction& b) {
return cryptonote::get_transaction_hash(a) == cryptonote::get_transaction_hash(b);
}
bool operator ==(const cryptonote::block& a, const cryptonote::block& b) {
return cryptonote::get_block_hash(a) == cryptonote::get_block_hash(b);
}
}
//--------------------------------------------------------------------------------
bool parse_hash256(const std::string str_hash, crypto::hash& hash)
{
std::string buf;
bool res = epee::string_tools::parse_hexstr_to_binbuff(str_hash, buf);
if (!res || buf.size() != sizeof(crypto::hash))
{
std::cout << "invalid hash format: <" << str_hash << '>' << std::endl;
return false;
}
else
{
buf.copy(reinterpret_cast<char *>(&hash), sizeof(crypto::hash));
return true;
}
}

View File

@ -0,0 +1,65 @@
// Copyright (c) 2012-2013 The Cryptonote developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#pragma once
#include "cryptonote_basic.h"
#include "crypto/crypto.h"
#include "crypto/hash.h"
namespace cryptonote {
/************************************************************************/
/* */
/************************************************************************/
template<class t_array>
struct array_hasher: std::unary_function<t_array&, std::size_t>
{
std::size_t operator()(const t_array& val) const
{
return boost::hash_range(&val.data[0], &val.data[sizeof(val.data)]);
}
};
#pragma pack(push, 1)
struct public_address_outer_blob
{
uint8_t m_ver;
account_public_address m_address;
uint8_t check_sum;
};
#pragma pack (pop)
/************************************************************************/
/* Cryptonote helper functions */
/************************************************************************/
size_t get_max_block_size();
size_t get_max_tx_size();
bool get_block_reward(size_t median_size, size_t current_block_size, uint64_t already_generated_coins, uint64_t &reward);
uint8_t get_account_address_checksum(const public_address_outer_blob& bl);
std::string get_account_address_as_str(const account_public_address& adr);
bool get_account_address_from_str(account_public_address& adr, const std::string& str);
bool is_coinbase(const transaction& tx);
bool operator ==(const cryptonote::transaction& a, const cryptonote::transaction& b);
bool operator ==(const cryptonote::block& a, const cryptonote::block& b);
}
template <class T>
std::ostream &print256(std::ostream &o, const T &v) {
return o << "<" << epee::string_tools::pod_to_hex(v) << ">";
}
bool parse_hash256(const std::string str_hash, crypto::hash& hash);
namespace crypto {
inline std::ostream &operator <<(std::ostream &o, const crypto::public_key &v) { return print256(o, v); }
inline std::ostream &operator <<(std::ostream &o, const crypto::secret_key &v) { return print256(o, v); }
inline std::ostream &operator <<(std::ostream &o, const crypto::key_derivation &v) { return print256(o, v); }
inline std::ostream &operator <<(std::ostream &o, const crypto::key_image &v) { return print256(o, v); }
inline std::ostream &operator <<(std::ostream &o, const crypto::signature &v) { return print256(o, v); }
inline std::ostream &operator <<(std::ostream &o, const crypto::hash &v) { return print256(o, v); }
}

View File

@ -0,0 +1,766 @@
// Copyright (c) 2012-2013 The Cryptonote developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "include_base_utils.h"
using namespace epee;
#include "cryptonote_format_utils.h"
#include <boost/foreach.hpp>
#include "cryptonote_config.h"
#include "miner.h"
#include "crypto/crypto.h"
#include "crypto/hash.h"
namespace cryptonote
{
//---------------------------------------------------------------
void get_transaction_prefix_hash(const transaction_prefix& tx, crypto::hash& h)
{
std::ostringstream s;
binary_archive<true> a(s);
::serialization::serialize(a, const_cast<transaction_prefix&>(tx));
crypto::cn_fast_hash(s.str().data(), s.str().size(), h);
}
//---------------------------------------------------------------
crypto::hash get_transaction_prefix_hash(const transaction_prefix& tx)
{
crypto::hash h = null_hash;
get_transaction_prefix_hash(tx, h);
return h;
}
//---------------------------------------------------------------
bool parse_and_validate_tx_from_blob(const blobdata& tx_blob, transaction& tx)
{
std::stringstream ss;
ss << tx_blob;
binary_archive<false> ba(ss);
bool r = ::serialization::serialize(ba, tx);
CHECK_AND_ASSERT_MES(r, false, "Failed to parse transaction from blob");
return true;
}
//---------------------------------------------------------------
bool parse_and_validate_tx_from_blob(const blobdata& tx_blob, transaction& tx, crypto::hash& tx_hash, crypto::hash& tx_prefix_hash)
{
std::stringstream ss;
ss << tx_blob;
binary_archive<false> ba(ss);
bool r = ::serialization::serialize(ba, tx);
CHECK_AND_ASSERT_MES(r, false, "Failed to parse transaction from blob");
//TODO: validate tx
crypto::cn_fast_hash(tx_blob.data(), tx_blob.size(), tx_hash);
get_transaction_prefix_hash(tx, tx_prefix_hash);
return true;
}
//---------------------------------------------------------------
bool construct_miner_tx(size_t height, size_t median_size, uint64_t already_generated_coins, size_t current_block_size, uint64_t fee, const account_public_address &miner_address, transaction& tx, const blobdata& extra_nonce, size_t max_outs) {
tx.vin.clear();
tx.vout.clear();
tx.extra.clear();
keypair txkey = keypair::generate();
add_tx_pub_key_to_extra(tx, txkey.pub);
if(!extra_nonce.empty())
if(!add_extra_nonce_to_tx_extra(tx.extra, extra_nonce))
return false;
txin_gen in;
in.height = height;
uint64_t block_reward;
if(!get_block_reward(median_size, current_block_size, already_generated_coins, block_reward))
{
LOG_PRINT_L0("Block is too big");
return false;
}
#if defined(DEBUG_CREATE_BLOCK_TEMPLATE)
LOG_PRINT_L1("Creating block template: reward " << block_reward <<
", fee " << fee)
#endif
block_reward += fee;
std::vector<uint64_t> out_amounts;
decompose_amount_into_digits(block_reward, DEFAULT_FEE,
[&out_amounts](uint64_t a_chunk) { out_amounts.push_back(a_chunk); },
[&out_amounts](uint64_t a_dust) { out_amounts.push_back(a_dust); });
CHECK_AND_ASSERT_MES(1 <= max_outs, false, "max_out must be non-zero");
while (max_outs < out_amounts.size())
{
out_amounts[out_amounts.size() - 2] += out_amounts.back();
out_amounts.resize(out_amounts.size() - 1);
}
uint64_t summary_amounts = 0;
for (size_t no = 0; no < out_amounts.size(); no++)
{
crypto::key_derivation derivation = AUTO_VAL_INIT(derivation);;
crypto::public_key out_eph_public_key = AUTO_VAL_INIT(out_eph_public_key);
bool r = crypto::generate_key_derivation(miner_address.m_view_public_key, txkey.sec, derivation);
CHECK_AND_ASSERT_MES(r, false, "while creating outs: failed to generate_key_derivation(" << miner_address.m_view_public_key << ", " << txkey.sec << ")");
r = crypto::derive_public_key(derivation, no, miner_address.m_spend_public_key, out_eph_public_key);
CHECK_AND_ASSERT_MES(r, false, "while creating outs: failed to derive_public_key(" << derivation << ", " << no << ", "<< miner_address.m_spend_public_key << ")");
txout_to_key tk;
tk.key = out_eph_public_key;
tx_out out;
summary_amounts += out.amount = out_amounts[no];
out.target = tk;
tx.vout.push_back(out);
}
CHECK_AND_ASSERT_MES(summary_amounts == block_reward, false, "Failed to construct miner tx, summary_amounts = " << summary_amounts << " not equal block_reward = " << block_reward);
tx.version = CURRENT_TRANSACTION_VERSION;
//lock
tx.unlock_time = height + CRYPTONOTE_MINED_MONEY_UNLOCK_WINDOW;
tx.vin.push_back(in);
//LOG_PRINT("MINER_TX generated ok, block_reward=" << print_money(block_reward) << "(" << print_money(block_reward - fee) << "+" << print_money(fee)
// << "), current_block_size=" << current_block_size << ", already_generated_coins=" << already_generated_coins << ", tx_id=" << get_transaction_hash(tx), LOG_LEVEL_2);
return true;
}
//---------------------------------------------------------------
bool generate_key_image_helper(const account_keys& ack, const crypto::public_key& tx_public_key, size_t real_output_index, keypair& in_ephemeral, crypto::key_image& ki)
{
crypto::key_derivation recv_derivation = AUTO_VAL_INIT(recv_derivation);
bool r = crypto::generate_key_derivation(tx_public_key, ack.m_view_secret_key, recv_derivation);
CHECK_AND_ASSERT_MES(r, false, "key image helper: failed to generate_key_derivation(" << tx_public_key << ", " << ack.m_view_secret_key << ")");
r = crypto::derive_public_key(recv_derivation, real_output_index, ack.m_account_address.m_spend_public_key, in_ephemeral.pub);
CHECK_AND_ASSERT_MES(r, false, "key image helper: failed to derive_public_key(" << recv_derivation << ", " << real_output_index << ", " << ack.m_account_address.m_spend_public_key << ")");
crypto::derive_secret_key(recv_derivation, real_output_index, ack.m_spend_secret_key, in_ephemeral.sec);
crypto::generate_key_image(in_ephemeral.pub, in_ephemeral.sec, ki);
return true;
}
//---------------------------------------------------------------
uint64_t power_integral(uint64_t a, uint64_t b)
{
if(b == 0)
return 1;
uint64_t total = a;
for(uint64_t i = 1; i != b; i++)
total *= a;
return total;
}
//---------------------------------------------------------------
bool parse_amount(uint64_t& amount, const std::string& str_amount_)
{
std::string str_amount = str_amount_;
boost::algorithm::trim(str_amount);
size_t point_index = str_amount.find_first_of('.');
size_t fraction_size;
if (std::string::npos != point_index)
{
fraction_size = str_amount.size() - point_index - 1;
while (CRYPTONOTE_DISPLAY_DECIMAL_POINT < fraction_size && '0' == str_amount.back())
{
str_amount.erase(str_amount.size() - 1, 1);
--fraction_size;
}
if (CRYPTONOTE_DISPLAY_DECIMAL_POINT < fraction_size)
return false;
str_amount.erase(point_index, 1);
}
else
{
fraction_size = 0;
}
if (str_amount.empty())
return false;
if (fraction_size < CRYPTONOTE_DISPLAY_DECIMAL_POINT)
{
str_amount.append(CRYPTONOTE_DISPLAY_DECIMAL_POINT - fraction_size, '0');
}
return string_tools::get_xtype_from_string(amount, str_amount);
}
//---------------------------------------------------------------
bool get_tx_fee(const transaction& tx, uint64_t & fee)
{
uint64_t amount_in = 0;
uint64_t amount_out = 0;
BOOST_FOREACH(auto& in, tx.vin)
{
CHECK_AND_ASSERT_MES(in.type() == typeid(txin_to_key), 0, "unexpected type id in transaction");
amount_in += boost::get<txin_to_key>(in).amount;
}
BOOST_FOREACH(auto& o, tx.vout)
amount_out += o.amount;
CHECK_AND_ASSERT_MES(amount_in >= amount_out, false, "transaction spend (" <<amount_in << ") more than it has (" << amount_out << ")");
fee = amount_in - amount_out;
return true;
}
//---------------------------------------------------------------
uint64_t get_tx_fee(const transaction& tx)
{
uint64_t r = 0;
if(!get_tx_fee(tx, r))
return 0;
return r;
}
//---------------------------------------------------------------
bool parse_tx_extra(const std::vector<uint8_t>& tx_extra, std::vector<tx_extra_field>& tx_extra_fields)
{
tx_extra_fields.clear();
if(tx_extra.empty())
return true;
std::string extra_str(reinterpret_cast<const char*>(tx_extra.data()), tx_extra.size());
std::istringstream iss(extra_str);
binary_archive<false> ar(iss);
bool eof = false;
while (!eof)
{
tx_extra_field field;
bool r = ::do_serialize(ar, field);
CHECK_AND_NO_ASSERT_MES(r, false, "failed to deserialize extra field. extra = " << string_tools::buff_to_hex_nodelimer(std::string(reinterpret_cast<const char*>(tx_extra.data()), tx_extra.size())));
tx_extra_fields.push_back(field);
std::ios_base::iostate state = iss.rdstate();
eof = (EOF == iss.peek());
iss.clear(state);
}
CHECK_AND_NO_ASSERT_MES(::serialization::check_stream_state(ar), false, "failed to deserialize extra field. extra = " << string_tools::buff_to_hex_nodelimer(std::string(reinterpret_cast<const char*>(tx_extra.data()), tx_extra.size())));
return true;
}
//---------------------------------------------------------------
crypto::public_key get_tx_pub_key_from_extra(const std::vector<uint8_t>& tx_extra)
{
std::vector<tx_extra_field> tx_extra_fields;
if (!parse_tx_extra(tx_extra, tx_extra_fields))
return null_pkey;
tx_extra_pub_key pub_key_field;
if(!find_tx_extra_field_by_type(tx_extra_fields, pub_key_field))
return null_pkey;
return pub_key_field.pub_key;
}
//---------------------------------------------------------------
crypto::public_key get_tx_pub_key_from_extra(const transaction& tx)
{
return get_tx_pub_key_from_extra(tx.extra);
}
//---------------------------------------------------------------
bool add_tx_pub_key_to_extra(transaction& tx, const crypto::public_key& tx_pub_key)
{
tx.extra.resize(tx.extra.size() + 1 + sizeof(crypto::public_key));
tx.extra[tx.extra.size() - 1 - sizeof(crypto::public_key)] = TX_EXTRA_TAG_PUBKEY;
*reinterpret_cast<crypto::public_key*>(&tx.extra[tx.extra.size() - sizeof(crypto::public_key)]) = tx_pub_key;
return true;
}
//---------------------------------------------------------------
bool add_extra_nonce_to_tx_extra(std::vector<uint8_t>& tx_extra, const blobdata& extra_nonce)
{
CHECK_AND_ASSERT_MES(extra_nonce.size() <= TX_EXTRA_NONCE_MAX_COUNT, false, "extra nonce could be 255 bytes max");
size_t start_pos = tx_extra.size();
tx_extra.resize(tx_extra.size() + 2 + extra_nonce.size());
//write tag
tx_extra[start_pos] = TX_EXTRA_NONCE;
//write len
++start_pos;
tx_extra[start_pos] = static_cast<uint8_t>(extra_nonce.size());
//write data
++start_pos;
memcpy(&tx_extra[start_pos], extra_nonce.data(), extra_nonce.size());
return true;
}
//---------------------------------------------------------------
void set_payment_id_to_tx_extra_nonce(blobdata& extra_nonce, const crypto::hash& payment_id)
{
extra_nonce.clear();
extra_nonce.push_back(TX_EXTRA_NONCE_PAYMENT_ID);
const uint8_t* payment_id_ptr = reinterpret_cast<const uint8_t*>(&payment_id);
std::copy(payment_id_ptr, payment_id_ptr + sizeof(payment_id), std::back_inserter(extra_nonce));
}
//---------------------------------------------------------------
bool get_payment_id_from_tx_extra_nonce(const blobdata& extra_nonce, crypto::hash& payment_id)
{
if(sizeof(crypto::hash) + 1 != extra_nonce.size())
return false;
if(TX_EXTRA_NONCE_PAYMENT_ID != extra_nonce[0])
return false;
payment_id = *reinterpret_cast<const crypto::hash*>(extra_nonce.data() + 1);
return true;
}
//---------------------------------------------------------------
bool construct_tx(const account_keys& sender_account_keys, const std::vector<tx_source_entry>& sources, const std::vector<tx_destination_entry>& destinations, std::vector<uint8_t> extra, transaction& tx, uint64_t unlock_time)
{
tx.vin.clear();
tx.vout.clear();
tx.signatures.clear();
tx.version = CURRENT_TRANSACTION_VERSION;
tx.unlock_time = unlock_time;
tx.extra = extra;
keypair txkey = keypair::generate();
add_tx_pub_key_to_extra(tx, txkey.pub);
struct input_generation_context_data
{
keypair in_ephemeral;
};
std::vector<input_generation_context_data> in_contexts;
uint64_t summary_inputs_money = 0;
//fill inputs
BOOST_FOREACH(const tx_source_entry& src_entr, sources)
{
if(src_entr.real_output >= src_entr.outputs.size())
{
LOG_ERROR("real_output index (" << src_entr.real_output << ")bigger than output_keys.size()=" << src_entr.outputs.size());
return false;
}
summary_inputs_money += src_entr.amount;
//key_derivation recv_derivation;
in_contexts.push_back(input_generation_context_data());
keypair& in_ephemeral = in_contexts.back().in_ephemeral;
crypto::key_image img;
if(!generate_key_image_helper(sender_account_keys, src_entr.real_out_tx_key, src_entr.real_output_in_tx_index, in_ephemeral, img))
return false;
//check that derivated key is equal with real output key
if( !(in_ephemeral.pub == src_entr.outputs[src_entr.real_output].second) )
{
LOG_ERROR("derived public key missmatch with output public key! "<< ENDL << "derived_key:"
<< string_tools::pod_to_hex(in_ephemeral.pub) << ENDL << "real output_public_key:"
<< string_tools::pod_to_hex(src_entr.outputs[src_entr.real_output].second) );
return false;
}
//put key image into tx input
txin_to_key input_to_key;
input_to_key.amount = src_entr.amount;
input_to_key.k_image = img;
//fill outputs array and use relative offsets
BOOST_FOREACH(const tx_source_entry::output_entry& out_entry, src_entr.outputs)
input_to_key.key_offsets.push_back(out_entry.first);
input_to_key.key_offsets = absolute_output_offsets_to_relative(input_to_key.key_offsets);
tx.vin.push_back(input_to_key);
}
// "Shuffle" outs
std::vector<tx_destination_entry> shuffled_dsts(destinations);
std::sort(shuffled_dsts.begin(), shuffled_dsts.end(), [](const tx_destination_entry& de1, const tx_destination_entry& de2) { return de1.amount < de2.amount; } );
uint64_t summary_outs_money = 0;
//fill outputs
size_t output_index = 0;
BOOST_FOREACH(const tx_destination_entry& dst_entr, shuffled_dsts)
{
CHECK_AND_ASSERT_MES(dst_entr.amount > 0, false, "Destination with wrong amount: " << dst_entr.amount);
crypto::key_derivation derivation;
crypto::public_key out_eph_public_key;
bool r = crypto::generate_key_derivation(dst_entr.addr.m_view_public_key, txkey.sec, derivation);
CHECK_AND_ASSERT_MES(r, false, "at creation outs: failed to generate_key_derivation(" << dst_entr.addr.m_view_public_key << ", " << txkey.sec << ")");
r = crypto::derive_public_key(derivation, output_index, dst_entr.addr.m_spend_public_key, out_eph_public_key);
CHECK_AND_ASSERT_MES(r, false, "at creation outs: failed to derive_public_key(" << derivation << ", " << output_index << ", "<< dst_entr.addr.m_spend_public_key << ")");
tx_out out;
out.amount = dst_entr.amount;
txout_to_key tk;
tk.key = out_eph_public_key;
out.target = tk;
tx.vout.push_back(out);
output_index++;
summary_outs_money += dst_entr.amount;
}
//check money
if(summary_outs_money > summary_inputs_money )
{
LOG_ERROR("Transaction inputs money ("<< summary_inputs_money << ") less than outputs money (" << summary_outs_money << ")");
return false;
}
//generate ring signatures
crypto::hash tx_prefix_hash;
get_transaction_prefix_hash(tx, tx_prefix_hash);
std::stringstream ss_ring_s;
size_t i = 0;
BOOST_FOREACH(const tx_source_entry& src_entr, sources)
{
ss_ring_s << "pub_keys:" << ENDL;
std::vector<const crypto::public_key*> keys_ptrs;
BOOST_FOREACH(const tx_source_entry::output_entry& o, src_entr.outputs)
{
keys_ptrs.push_back(&o.second);
ss_ring_s << o.second << ENDL;
}
tx.signatures.push_back(std::vector<crypto::signature>());
std::vector<crypto::signature>& sigs = tx.signatures.back();
sigs.resize(src_entr.outputs.size());
crypto::generate_ring_signature(tx_prefix_hash, boost::get<txin_to_key>(tx.vin[i]).k_image, keys_ptrs, in_contexts[i].in_ephemeral.sec, src_entr.real_output, sigs.data());
ss_ring_s << "signatures:" << ENDL;
std::for_each(sigs.begin(), sigs.end(), [&](const crypto::signature& s){ss_ring_s << s << ENDL;});
ss_ring_s << "prefix_hash:" << tx_prefix_hash << ENDL << "in_ephemeral_key: " << in_contexts[i].in_ephemeral.sec << ENDL << "real_output: " << src_entr.real_output;
i++;
}
LOG_PRINT2("construct_tx.log", "transaction_created: " << get_transaction_hash(tx) << ENDL << obj_to_json_str(tx) << ENDL << ss_ring_s.str() , LOG_LEVEL_3);
return true;
}
//---------------------------------------------------------------
bool get_inputs_money_amount(const transaction& tx, uint64_t& money)
{
money = 0;
BOOST_FOREACH(const auto& in, tx.vin)
{
CHECKED_GET_SPECIFIC_VARIANT(in, const txin_to_key, tokey_in, false);
money += tokey_in.amount;
}
return true;
}
//---------------------------------------------------------------
uint64_t get_block_height(const block& b)
{
CHECK_AND_ASSERT_MES(b.miner_tx.vin.size() == 1, 0, "wrong miner tx in block: " << get_block_hash(b) << ", b.miner_tx.vin.size() != 1");
CHECKED_GET_SPECIFIC_VARIANT(b.miner_tx.vin[0], const txin_gen, coinbase_in, 0);
return coinbase_in.height;
}
//---------------------------------------------------------------
bool check_inputs_types_supported(const transaction& tx)
{
BOOST_FOREACH(const auto& in, tx.vin)
{
CHECK_AND_ASSERT_MES(in.type() == typeid(txin_to_key), false, "wrong variant type: "
<< in.type().name() << ", expected " << typeid(txin_to_key).name()
<< ", in transaction id=" << get_transaction_hash(tx));
}
return true;
}
//-----------------------------------------------------------------------------------------------
bool check_outs_valid(const transaction& tx)
{
BOOST_FOREACH(const tx_out& out, tx.vout)
{
CHECK_AND_ASSERT_MES(out.target.type() == typeid(txout_to_key), false, "wrong variant type: "
<< out.target.type().name() << ", expected " << typeid(txout_to_key).name()
<< ", in transaction id=" << get_transaction_hash(tx));
CHECK_AND_NO_ASSERT_MES(0 < out.amount, false, "zero amount ouput in transaction id=" << get_transaction_hash(tx));
if(!check_key(boost::get<txout_to_key>(out.target).key))
return false;
}
return true;
}
//-----------------------------------------------------------------------------------------------
bool check_money_overflow(const transaction& tx)
{
return check_inputs_overflow(tx) && check_outs_overflow(tx);
}
//---------------------------------------------------------------
bool check_inputs_overflow(const transaction& tx)
{
uint64_t money = 0;
BOOST_FOREACH(const auto& in, tx.vin)
{
CHECKED_GET_SPECIFIC_VARIANT(in, const txin_to_key, tokey_in, false);
if(money > tokey_in.amount + money)
return false;
money += tokey_in.amount;
}
return true;
}
//---------------------------------------------------------------
bool check_outs_overflow(const transaction& tx)
{
uint64_t money = 0;
BOOST_FOREACH(const auto& o, tx.vout)
{
if(money > o.amount + money)
return false;
money += o.amount;
}
return true;
}
//---------------------------------------------------------------
uint64_t get_outs_money_amount(const transaction& tx)
{
uint64_t outputs_amount = 0;
BOOST_FOREACH(const auto& o, tx.vout)
outputs_amount += o.amount;
return outputs_amount;
}
//---------------------------------------------------------------
std::string short_hash_str(const crypto::hash& h)
{
std::string res = string_tools::pod_to_hex(h);
CHECK_AND_ASSERT_MES(res.size() == 64, res, "wrong hash256 with string_tools::pod_to_hex conversion");
auto erased_pos = res.erase(8, 48);
res.insert(8, "....");
return res;
}
//---------------------------------------------------------------
bool is_out_to_acc(const account_keys& acc, const txout_to_key& out_key, const crypto::public_key& tx_pub_key, size_t output_index)
{
crypto::key_derivation derivation;
generate_key_derivation(tx_pub_key, acc.m_view_secret_key, derivation);
crypto::public_key pk;
derive_public_key(derivation, output_index, acc.m_account_address.m_spend_public_key, pk);
return pk == out_key.key;
}
//---------------------------------------------------------------
bool lookup_acc_outs(const account_keys& acc, const transaction& tx, std::vector<size_t>& outs, uint64_t& money_transfered)
{
crypto::public_key tx_pub_key = get_tx_pub_key_from_extra(tx);
if(null_pkey == tx_pub_key)
return false;
return lookup_acc_outs(acc, tx, tx_pub_key, outs, money_transfered);
}
//---------------------------------------------------------------
bool lookup_acc_outs(const account_keys& acc, const transaction& tx, const crypto::public_key& tx_pub_key, std::vector<size_t>& outs, uint64_t& money_transfered)
{
money_transfered = 0;
size_t i = 0;
BOOST_FOREACH(const tx_out& o, tx.vout)
{
CHECK_AND_ASSERT_MES(o.target.type() == typeid(txout_to_key), false, "wrong type id in transaction out" );
if(is_out_to_acc(acc, boost::get<txout_to_key>(o.target), tx_pub_key, i))
{
outs.push_back(i);
money_transfered += o.amount;
}
i++;
}
return true;
}
//---------------------------------------------------------------
void get_blob_hash(const blobdata& blob, crypto::hash& res)
{
cn_fast_hash(blob.data(), blob.size(), res);
}
//---------------------------------------------------------------
std::string print_money(uint64_t amount)
{
std::string s = std::to_string(amount);
if(s.size() < CRYPTONOTE_DISPLAY_DECIMAL_POINT+1)
{
s.insert(0, CRYPTONOTE_DISPLAY_DECIMAL_POINT+1 - s.size(), '0');
}
s.insert(s.size() - CRYPTONOTE_DISPLAY_DECIMAL_POINT, ".");
return s;
}
//---------------------------------------------------------------
crypto::hash get_blob_hash(const blobdata& blob)
{
crypto::hash h = null_hash;
get_blob_hash(blob, h);
return h;
}
//---------------------------------------------------------------
crypto::hash get_transaction_hash(const transaction& t)
{
crypto::hash h = null_hash;
size_t blob_size = 0;
get_object_hash(t, h, blob_size);
return h;
}
//---------------------------------------------------------------
bool get_transaction_hash(const transaction& t, crypto::hash& res)
{
size_t blob_size = 0;
return get_object_hash(t, res, blob_size);
}
bool get_transaction_hash(const bb_transaction& t, crypto::hash& res)
{
size_t blob_size = 0;
return get_object_hash(t, res, blob_size);
}
//---------------------------------------------------------------
bool get_transaction_hash(const transaction& t, crypto::hash& res, size_t& blob_size)
{
return get_object_hash(t, res, blob_size);
}
//---------------------------------------------------------------
blobdata get_block_hashing_blob(const block& b)
{
blobdata blob = t_serializable_object_to_blob(static_cast<block_header>(b));
crypto::hash tree_root_hash = get_tx_tree_hash(b);
blob.append((const char*)&tree_root_hash, sizeof(tree_root_hash ));
blob.append(tools::get_varint_data(b.tx_hashes.size()+1));
return blob;
}
blobdata get_block_hashing_blob(const bb_block& b)
{
blobdata blob = t_serializable_object_to_blob(static_cast<bb_block_header>(b));
crypto::hash tree_root_hash = get_tx_tree_hash(b);
blob.append((const char*)&tree_root_hash, sizeof(tree_root_hash ));
blob.append(tools::get_varint_data(b.tx_hashes.size()+1));
return blob;
}
//---------------------------------------------------------------
bool get_block_hash(const block& b, crypto::hash& res)
{
return get_object_hash(get_block_hashing_blob(b), res);
}
//---------------------------------------------------------------
crypto::hash get_block_hash(const block& b)
{
crypto::hash p = null_hash;
get_block_hash(b, p);
return p;
}
//---------------------------------------------------------------
bool generate_genesis_block(block& bl)
{
//genesis block
bl = boost::value_initialized<block>();
account_public_address ac = boost::value_initialized<account_public_address>();
std::vector<size_t> sz;
construct_miner_tx(0, 0, 0, 0, 0, ac, bl.miner_tx); // zero fee in genesis
blobdata txb = tx_to_blob(bl.miner_tx);
std::string hex_tx_represent = string_tools::buff_to_hex_nodelimer(txb);
//hard code coinbase tx in genesis block, because "tru" generating tx use random, but genesis should be always the same
std::string genesis_coinbase_tx_hex = "013c01ff0001ffffffffffff03029b2e4c0281c0b02e7c53291a94d1d0cbff8883f8024f5142ee494ffbbd08807121017767aafcde9be00dcfd098715ebcf7f410daebc582fda69d24a28e9d0bc890d1";
blobdata tx_bl;
string_tools::parse_hexstr_to_binbuff(genesis_coinbase_tx_hex, tx_bl);
bool r = parse_and_validate_tx_from_blob(tx_bl, bl.miner_tx);
CHECK_AND_ASSERT_MES(r, false, "failed to parse coinbase tx from hard coded blob");
bl.major_version = CURRENT_BLOCK_MAJOR_VERSION;
bl.minor_version = CURRENT_BLOCK_MINOR_VERSION;
bl.timestamp = 0;
bl.nonce = 10000;
miner::find_nonce_for_given_block(bl, 1, 0);
return true;
}
//---------------------------------------------------------------
bool get_block_longhash(const block& b, crypto::hash& res, uint64_t height)
{
block b_local = b; //workaround to avoid const errors with do_serialize
blobdata bd = get_block_hashing_blob(b);
crypto::cn_slow_hash(bd.data(), bd.size(), res);
return true;
}
//---------------------------------------------------------------
std::vector<uint64_t> relative_output_offsets_to_absolute(const std::vector<uint64_t>& off)
{
std::vector<uint64_t> res = off;
for(size_t i = 1; i < res.size(); i++)
res[i] += res[i-1];
return res;
}
//---------------------------------------------------------------
std::vector<uint64_t> absolute_output_offsets_to_relative(const std::vector<uint64_t>& off)
{
std::vector<uint64_t> res = off;
if(!off.size())
return res;
std::sort(res.begin(), res.end());//just to be sure, actually it is already should be sorted
for(size_t i = res.size()-1; i != 0; i--)
res[i] -= res[i-1];
return res;
}
//---------------------------------------------------------------
crypto::hash get_block_longhash(const block& b, uint64_t height)
{
crypto::hash p = null_hash;
get_block_longhash(b, p, height);
return p;
}
//---------------------------------------------------------------
bool parse_and_validate_block_from_blob(const blobdata& b_blob, block& b)
{
std::stringstream ss;
ss << b_blob;
binary_archive<false> ba(ss);
bool r = ::serialization::serialize(ba, b);
CHECK_AND_ASSERT_MES(r, false, "Failed to parse block from blob");
return true;
}
bool parse_and_validate_block_from_blob(const blobdata& b_blob, bb_block& b)
{
std::stringstream ss;
ss << b_blob;
binary_archive<false> ba(ss);
bool r = ::serialization::serialize(ba, b);
CHECK_AND_ASSERT_MES(r, false, "Failed to parse block from blob");
return true;
}
//---------------------------------------------------------------
blobdata block_to_blob(const block& b)
{
return t_serializable_object_to_blob(b);
}
//---------------------------------------------------------------
bool block_to_blob(const block& b, blobdata& b_blob)
{
return t_serializable_object_to_blob(b, b_blob);
}
//---------------------------------------------------------------
blobdata tx_to_blob(const transaction& tx)
{
return t_serializable_object_to_blob(tx);
}
//---------------------------------------------------------------
bool tx_to_blob(const transaction& tx, blobdata& b_blob)
{
return t_serializable_object_to_blob(tx, b_blob);
}
//---------------------------------------------------------------
void get_tx_tree_hash(const std::vector<crypto::hash>& tx_hashes, crypto::hash& h)
{
tree_hash(tx_hashes.data(), tx_hashes.size(), h);
}
//---------------------------------------------------------------
crypto::hash get_tx_tree_hash(const std::vector<crypto::hash>& tx_hashes)
{
crypto::hash h = null_hash;
get_tx_tree_hash(tx_hashes, h);
return h;
}
//---------------------------------------------------------------
crypto::hash get_tx_tree_hash(const block& b)
{
std::vector<crypto::hash> txs_ids;
crypto::hash h = null_hash;
size_t bl_sz = 0;
get_transaction_hash(b.miner_tx, h, bl_sz);
txs_ids.push_back(h);
BOOST_FOREACH(auto& th, b.tx_hashes)
txs_ids.push_back(th);
return get_tx_tree_hash(txs_ids);
}
crypto::hash get_tx_tree_hash(const bb_block& b)
{
std::vector<crypto::hash> txs_ids;
crypto::hash h = null_hash;
get_transaction_hash(b.miner_tx, h);
txs_ids.push_back(h);
BOOST_FOREACH(auto& th, b.tx_hashes)
txs_ids.push_back(th);
return get_tx_tree_hash(txs_ids);
}
//---------------------------------------------------------------
}

View File

@ -0,0 +1,30 @@
// Copyright (c) 2012-2013 The Cryptonote developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#pragma once
#include "../hash.h"
#include "../wild_keccak.h"
namespace cryptonote
{
template<typename callback_t>
bool get_blob_longhash_bb(const blobdata& bd, crypto::hash& res, uint64_t height, callback_t accessor)
{
crypto::wild_keccak_dbl<crypto::mul_f>(reinterpret_cast<const uint8_t*>(bd.data()), bd.size(), reinterpret_cast<uint8_t*>(&res), sizeof(res), [&](crypto::state_t_m& st, crypto::mixin_t& mix)
{
if(!height)
{
memset(&mix, 0, sizeof(mix));
return;
}
#define GET_H(index) accessor(st[index])
for(size_t i = 0; i!=6; i++)
{
*(crypto::hash*)&mix[i*4] = XOR_4(GET_H(i*4), GET_H(i*4+1), GET_H(i*4+2), GET_H(i*4+3));
}
});
return true;
}
}

View File

@ -0,0 +1,152 @@
// Copyright (c) 2012-2013 The Cryptonote developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#pragma once
#include <list>
#include "serialization/keyvalue_serialization.h"
#include "cryptonote_core/cryptonote_basic.h"
#include "cryptonote_protocol/blobdatatype.h"
namespace cryptonote
{
#define BC_COMMANDS_POOL_BASE 2000
/************************************************************************/
/* */
/************************************************************************/
struct block_complete_entry
{
blobdata block;
std::list<blobdata> txs;
BEGIN_KV_SERIALIZE_MAP()
KV_SERIALIZE(block)
KV_SERIALIZE(txs)
END_KV_SERIALIZE_MAP()
};
/************************************************************************/
/* */
/************************************************************************/
struct NOTIFY_NEW_BLOCK
{
const static int ID = BC_COMMANDS_POOL_BASE + 1;
struct request
{
block_complete_entry b;
uint64_t current_blockchain_height;
uint32_t hop;
BEGIN_KV_SERIALIZE_MAP()
KV_SERIALIZE(b)
KV_SERIALIZE(current_blockchain_height)
KV_SERIALIZE(hop)
END_KV_SERIALIZE_MAP()
};
};
/************************************************************************/
/* */
/************************************************************************/
struct NOTIFY_NEW_TRANSACTIONS
{
const static int ID = BC_COMMANDS_POOL_BASE + 2;
struct request
{
std::list<blobdata> txs;
BEGIN_KV_SERIALIZE_MAP()
KV_SERIALIZE(txs)
END_KV_SERIALIZE_MAP()
};
};
/************************************************************************/
/* */
/************************************************************************/
struct NOTIFY_REQUEST_GET_OBJECTS
{
const static int ID = BC_COMMANDS_POOL_BASE + 3;
struct request
{
std::list<crypto::hash> txs;
std::list<crypto::hash> blocks;
BEGIN_KV_SERIALIZE_MAP()
KV_SERIALIZE_CONTAINER_POD_AS_BLOB(txs)
KV_SERIALIZE_CONTAINER_POD_AS_BLOB(blocks)
END_KV_SERIALIZE_MAP()
};
};
struct NOTIFY_RESPONSE_GET_OBJECTS
{
const static int ID = BC_COMMANDS_POOL_BASE + 4;
struct request
{
std::list<blobdata> txs;
std::list<block_complete_entry> blocks;
std::list<crypto::hash> missed_ids;
uint64_t current_blockchain_height;
BEGIN_KV_SERIALIZE_MAP()
KV_SERIALIZE(txs)
KV_SERIALIZE(blocks)
KV_SERIALIZE_CONTAINER_POD_AS_BLOB(missed_ids)
KV_SERIALIZE(current_blockchain_height)
END_KV_SERIALIZE_MAP()
};
};
struct CORE_SYNC_DATA
{
uint64_t current_height;
crypto::hash top_id;
BEGIN_KV_SERIALIZE_MAP()
KV_SERIALIZE(current_height)
KV_SERIALIZE_VAL_POD_AS_BLOB(top_id)
END_KV_SERIALIZE_MAP()
};
struct NOTIFY_REQUEST_CHAIN
{
const static int ID = BC_COMMANDS_POOL_BASE + 6;
struct request
{
std::list<crypto::hash> block_ids; /*IDs of the first 10 blocks are sequential, next goes with pow(2,n) offset, like 2, 4, 8, 16, 32, 64 and so on, and the last one is always genesis block */
BEGIN_KV_SERIALIZE_MAP()
KV_SERIALIZE_CONTAINER_POD_AS_BLOB(block_ids)
END_KV_SERIALIZE_MAP()
};
};
struct NOTIFY_RESPONSE_CHAIN_ENTRY
{
const static int ID = BC_COMMANDS_POOL_BASE + 7;
struct request
{
uint64_t start_height;
uint64_t total_height;
std::list<crypto::hash> m_block_ids;
BEGIN_KV_SERIALIZE_MAP()
KV_SERIALIZE(start_height)
KV_SERIALIZE(total_height)
KV_SERIALIZE_CONTAINER_POD_AS_BLOB(m_block_ids)
END_KV_SERIALIZE_MAP()
};
};
}

View File

@ -1,4 +1,22 @@
#pragma once
#include "hash-ops.h"
typedef unsigned char BitSequence;
typedef unsigned long long DataLength;
#ifdef __cplusplus
#include <string>
typedef std::string blobdata;
namespace crypto {
#pragma pack(push, 1)
class hash {
char data[HASH_SIZE];
};
#pragma pack(pop)
}
#endif

View File

@ -0,0 +1,119 @@
// keccak.c
// 19-Nov-11 Markku-Juhani O. Saarinen <mjos@iki.fi>
// A baseline Keccak (3rd round) implementation.
// Memory-hard extension of keccak for PoW
// Copyright (c) 2014 The Boolberry developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "wild_keccak.h"
namespace crypto
{
const uint64_t keccakf_rndc[24] =
{
0x0000000000000001, 0x0000000000008082, 0x800000000000808a,
0x8000000080008000, 0x000000000000808b, 0x0000000080000001,
0x8000000080008081, 0x8000000000008009, 0x000000000000008a,
0x0000000000000088, 0x0000000080008009, 0x000000008000000a,
0x000000008000808b, 0x800000000000008b, 0x8000000000008089,
0x8000000000008003, 0x8000000000008002, 0x8000000000000080,
0x000000000000800a, 0x800000008000000a, 0x8000000080008081,
0x8000000000008080, 0x0000000080000001, 0x8000000080008008
};
const int keccakf_rotc[24] =
{
1, 3, 6, 10, 15, 21, 28, 36, 45, 55, 2, 14,
27, 41, 56, 8, 25, 43, 62, 18, 39, 61, 20, 44
};
const int keccakf_piln[24] =
{
10, 7, 11, 17, 18, 3, 5, 16, 8, 21, 24, 4,
15, 23, 19, 13, 12, 2, 20, 14, 22, 9, 6, 1
};
// update the state with given number of rounds
void regular_f::keccakf(uint64_t st[25], int rounds)
{
int i, j, round;
uint64_t t, bc[5];
for (round = 0; round < rounds; round++) {
// Theta
for (i = 0; i < 5; i++)
bc[i] = st[i] ^ st[i + 5] ^ st[i + 10] ^ st[i + 15] ^ st[i + 20];
for (i = 0; i < 5; i++) {
t = bc[(i + 4) % 5] ^ ROTL64(bc[(i + 1) % 5], 1);
for (j = 0; j < 25; j += 5)
st[j + i] ^= t;
}
// Rho Pi
t = st[1];
for (i = 0; i < 24; i++) {
j = keccakf_piln[i];
bc[0] = st[j];
st[j] = ROTL64(t, keccakf_rotc[i]);
t = bc[0];
}
// Chi
for (j = 0; j < 25; j += 5) {
for (i = 0; i < 5; i++)
bc[i] = st[j + i];
for (i = 0; i < 5; i++)
st[j + i] ^= (~bc[(i + 1) % 5]) & bc[(i + 2) % 5];
}
// Iota
st[0] ^= keccakf_rndc[round];
}
}
void mul_f::keccakf(uint64_t st[25], int rounds)
{
int i, j, round;
uint64_t t, bc[5];
for (round = 0; round < rounds; round++) {
// Theta
for (i = 0; i < 5; i++)
{
bc[i] = st[i] ^ st[i + 5] ^ st[i + 10] * st[i + 15] * st[i + 20];//surprise
}
for (i = 0; i < 5; i++) {
t = bc[(i + 4) % 5] ^ ROTL64(bc[(i + 1) % 5], 1);
for (j = 0; j < 25; j += 5)
st[j + i] ^= t;
}
// Rho Pi
t = st[1];
for (i = 0; i < 24; i++) {
j = keccakf_piln[i];
bc[0] = st[j];
st[j] = ROTL64(t, keccakf_rotc[i]);
t = bc[0];
}
// Chi
for (j = 0; j < 25; j += 5) {
for (i = 0; i < 5; i++)
bc[i] = st[j + i];
for (i = 0; i < 5; i++)
st[j + i] ^= (~bc[(i + 1) % 5]) & bc[(i + 2) % 5];
}
// Iota
st[0] ^= keccakf_rndc[round];
}
}
}

View File

@ -0,0 +1,168 @@
// keccak.h
// 19-Nov-11 Markku-Juhani O. Saarinen <mjos@iki.fi>
// Copyright (c) 2014 The Boolberry developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#pragma once
#include <stdint.h>
#include <string.h>
#include "hash.h"
#ifndef KECCAK_ROUNDS
#define KECCAK_ROUNDS 24
#endif
#ifndef ROTL64
#define ROTL64(x, y) (((x) << (y)) | ((x) >> (64 - (y))))
#endif
// compute a keccak hash (md) of given byte length from "in"
#define KK_MIXIN_SIZE 24
namespace crypto
{
template<typename pod_operand_a, typename pod_operand_b>
pod_operand_a xor_pod(const pod_operand_a& a, const pod_operand_b& b)
{
static_assert(sizeof(pod_operand_a) == sizeof(pod_operand_b), "invalid xor_h usage: different sizes");
static_assert(sizeof(pod_operand_a)%8 == 0, "invalid xor_h usage: wrong size");
hash r;
for(size_t i = 0; i != 4; i++)
{
((uint64_t*)&r)[i] = ((const uint64_t*)&a)[i] ^ ((const uint64_t*)&b)[i];
}
return r;
}
#define XOR_2(A, B) crypto::xor_pod(A, B)
#define XOR_3(A, B, C) crypto::xor_pod(A, XOR_2(B, C))
#define XOR_4(A, B, C, D) crypto::xor_pod(A, XOR_3(B, C, D))
#define XOR_5(A, B, C, D, E) crypto::xor_pod(A, XOR_4(B, C, D, E))
#define XOR_8(A, B, C, D, F, G, H, I) crypto::xor_pod(XOR_4(A, B, C, D), XOR_4(F, G, H, I))
typedef uint64_t state_t_m[25];
typedef uint64_t mixin_t[KK_MIXIN_SIZE];
//with multiplication, for tests
template<class f_traits>
int keccak_generic(const uint8_t *in, size_t inlen, uint8_t *md, size_t mdlen)
{
state_t_m st;
uint8_t temp[144];
size_t i, rsiz, rsizw;
rsiz = sizeof(state_t_m) == mdlen ? HASH_DATA_AREA : 200 - 2 * mdlen;
rsizw = rsiz / 8;
memset(st, 0, sizeof(st));
for ( ; inlen >= rsiz; inlen -= rsiz, in += rsiz) {
for (i = 0; i < rsizw; i++)
st[i] ^= ((uint64_t *) in)[i];
f_traits::keccakf(st, KECCAK_ROUNDS);
}
// last block and padding
memcpy(temp, in, inlen);
temp[inlen++] = 1;
memset(temp + inlen, 0, rsiz - inlen);
temp[rsiz - 1] |= 0x80;
for (i = 0; i < rsizw; i++)
st[i] ^= ((uint64_t *) temp)[i];
f_traits::keccakf(st, KECCAK_ROUNDS);
memcpy(md, st, mdlen);
return 0;
}
template<class f_traits, class callback_t>
int wild_keccak(const uint8_t *in, size_t inlen, uint8_t *md, size_t mdlen, callback_t cb)
{
state_t_m st;
uint8_t temp[144];
uint64_t rsiz, rsizw;
rsiz = sizeof(state_t_m) == mdlen ? HASH_DATA_AREA : 200 - 2 * mdlen;
rsizw = rsiz / 8;
memset(&st[0], 0, 25*sizeof(st[0]));
for ( ; inlen >= rsiz; inlen -= rsiz, in += rsiz)
{
for (size_t i = 0; i < rsizw; i++)
st[i] ^= ((uint64_t *) in)[i];
for(size_t ll = 0; ll != KECCAK_ROUNDS; ll++)
{
if(ll != 0)
{//skip first round
mixin_t mix_in;
cb(st, mix_in);
for (size_t k = 0; k < KK_MIXIN_SIZE; k++)
st[k] ^= mix_in[k];
}
f_traits::keccakf(st, 1);
}
}
// last block and padding
memcpy(temp, in, inlen);
temp[inlen++] = 1;
memset(temp + inlen, 0, rsiz - inlen);
temp[rsiz - 1] |= 0x80;
for (size_t i = 0; i < rsizw; i++)
st[i] ^= ((uint64_t *) temp)[i];
for(size_t ll = 0; ll != KECCAK_ROUNDS; ll++)
{
if(ll != 0)
{//skip first state with
mixin_t mix_in;
cb(st, mix_in);
for (size_t k = 0; k < KK_MIXIN_SIZE; k++)
st[k] ^= mix_in[k];
}
f_traits::keccakf(st, 1);
}
memcpy(md, st, mdlen);
return 0;
}
template<class f_traits, class callback_t>
int wild_keccak_dbl(const uint8_t *in, size_t inlen, uint8_t *md, size_t mdlen, callback_t cb)
{
//Satoshi's classic
wild_keccak<f_traits>(in, inlen, md, mdlen, cb);
wild_keccak<f_traits>(md, mdlen, md, mdlen, cb);
return 0;
}
class regular_f
{
public:
static void keccakf(uint64_t st[25], int rounds);
};
class mul_f
{
public:
static void keccakf(uint64_t st[25], int rounds);
};
}

View File

@ -178,6 +178,6 @@ void cryptonight_hash(const char* input, char* output, uint32_t len) {
void cryptonight_fast_hash(const char* input, char* output, uint32_t len) {
union hash_state state;
hash_process(&state, input, len);
hash_process(&state, (const uint8_t*) input, len);
memcpy(output, &state, HASH_SIZE);
}

View File

@ -21,6 +21,8 @@ extern "C" {
#include "x13.h"
}
#include "boolberry.h"
using namespace node;
using namespace v8;
@ -445,6 +447,41 @@ Handle<Value> x13(const Arguments& args) {
return scope.Close(buff->handle_);
}
Handle<Value> boolberry(const Arguments& args) {
HandleScope scope;
if (args.Length() < 2)
return except("You must provide two arguments.");
Local<Object> target = args[0]->ToObject();
Local<Object> target_spad = args[1]->ToObject();
uint32_t height = 1;
if(!Buffer::HasInstance(target))
return except("Argument 1 should be a buffer object.");
if(!Buffer::HasInstance(target_spad))
return except("Argument 2 should be a buffer object.");
if(args.Length() >= 3)
if(args[2]->IsUint32())
height = args[2]->ToUint32()->Uint32Value();
else
return except("Argument 3 should be an unsigned integer.");
char * input = Buffer::Data(target);
char * scratchpad = Buffer::Data(target_spad);
char output[32];
uint32_t input_len = Buffer::Length(target);
uint64_t spad_len = Buffer::Length(target_spad);
boolberry_hash(input, input_len, scratchpad, spad_len, output, height);
Buffer* buff = Buffer::New(output, 32);
return scope.Close(buff->handle_);
}
void init(Handle<Object> exports) {
exports->Set(String::NewSymbol("quark"), FunctionTemplate::New(quark)->GetFunction());
exports->Set(String::NewSymbol("x11"), FunctionTemplate::New(x11)->GetFunction());
@ -463,6 +500,7 @@ void init(Handle<Object> exports) {
exports->Set(String::NewSymbol("shavite3"), FunctionTemplate::New(shavite3)->GetFunction());
exports->Set(String::NewSymbol("cryptonight"), FunctionTemplate::New(cryptonight)->GetFunction());
exports->Set(String::NewSymbol("x13"), FunctionTemplate::New(x13)->GetFunction());
exports->Set(String::NewSymbol("boolberry"), FunctionTemplate::New(boolberry)->GetFunction());
}
NODE_MODULE(multihashing, init)