diff options
33 files changed, 1368 insertions, 436 deletions
@@ -61,6 +61,8 @@ The Monero donation address is: `44AFFq5kSiGBoZ4NMDwYtN18obc8AemS33DBLWs3H7otXft The Bitcoin donation address is: `1KTexdemPdxSBcG55heUuTjDRYqbC5ZL8H` +*Note: you can easily donate XMR to the Monero donation address by using the `donate` command. Type `help` in the command-line wallet for details.* + Core development funding and/or some supporting services are also graciously provided by sponsors: [<img width="80" src="https://static.getmonero.org/images/sponsors/mymonero.png"/>](https://mymonero.com) diff --git a/external/boost/archive/portable_binary_archive.hpp b/external/boost/archive/portable_binary_archive.hpp new file mode 100644 index 000000000..560ef121b --- /dev/null +++ b/external/boost/archive/portable_binary_archive.hpp @@ -0,0 +1,52 @@ +#ifndef PORTABLE_BINARY_ARCHIVE_HPP
+#define PORTABLE_BINARY_ARCHIVE_HPP
+
+// (C) Copyright 2002 Robert Ramey - http://www.rrsd.com .
+// Use, modification and distribution is subject to the Boost Software
+// License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
+// http://www.boost.org/LICENSE_1_0.txt)
+
+// MS compatible compilers support #pragma once
+#if defined(_MSC_VER)
+# pragma once
+#endif
+
+#include <boost/config.hpp>
+#include <boost/cstdint.hpp>
+#include <boost/static_assert.hpp>
+
+#include <climits>
+#if CHAR_BIT != 8
+#error This code assumes an eight-bit byte.
+#endif
+
+#include <boost/archive/basic_archive.hpp>
+#include <boost/detail/endian.hpp>
+
+#include <boost/archive/impl/archive_serializer_map.ipp>
+
+namespace boost { namespace archive {
+
+enum portable_binary_archive_flags {
+ endian_big = 0x4000,
+ endian_little = 0x8000
+};
+
+//#if ( endian_big <= boost::archive::flags_last )
+//#error archive flags conflict
+//#endif
+
+inline void
+reverse_bytes(char size, char *address){
+ char * first = address;
+ char * last = first + size - 1;
+ for(;first < last;++first, --last){
+ char x = *last;
+ *last = *first;
+ *first = x;
+ }
+}
+
+} }
+
+#endif // PORTABLE_BINARY_ARCHIVE_HPP
diff --git a/external/boost/archive/portable_binary_iarchive.hpp b/external/boost/archive/portable_binary_iarchive.hpp new file mode 100644 index 000000000..c33085b05 --- /dev/null +++ b/external/boost/archive/portable_binary_iarchive.hpp @@ -0,0 +1,340 @@ +#ifndef PORTABLE_BINARY_IARCHIVE_HPP
+#define PORTABLE_BINARY_IARCHIVE_HPP
+
+// MS compatible compilers support #pragma once
+#if defined(_MSC_VER)
+# pragma once
+#endif
+
+#if defined(_MSC_VER)
+#pragma warning( push )
+#pragma warning( disable : 4244 )
+#endif
+
+/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////8
+// portable_binary_iarchive.hpp
+
+// (C) Copyright 2002-7 Robert Ramey - http://www.rrsd.com .
+// Use, modification and distribution is subject to the Boost Software
+// License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
+// http://www.boost.org/LICENSE_1_0.txt)
+
+// See http://www.boost.org for updates, documentation, and revision history.
+
+#include <istream>
+#include <boost/serialization/string.hpp>
+#include <boost/serialization/item_version_type.hpp>
+#include <boost/archive/archive_exception.hpp>
+#include <boost/archive/basic_binary_iprimitive.hpp>
+#include <boost/archive/detail/common_iarchive.hpp>
+#include <boost/archive/detail/register_archive.hpp>
+
+#include <boost/archive/portable_binary_archive.hpp>
+#include <boost/archive/impl/basic_binary_iprimitive.ipp>
+
+namespace boost { namespace archive {
+
+/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////8
+// exception to be thrown if integer read from archive doesn't fit
+// variable being loaded
+class portable_binary_iarchive_exception :
+ public boost::archive::archive_exception
+{
+public:
+ enum exception_code {
+ incompatible_integer_size
+ } m_exception_code ;
+ portable_binary_iarchive_exception(exception_code c = incompatible_integer_size ) :
+ boost::archive::archive_exception(boost::archive::archive_exception::other_exception),
+ m_exception_code(c)
+ {}
+ virtual const char *what( ) const throw( )
+ {
+ const char *msg = "programmer error";
+ switch(m_exception_code){
+ case incompatible_integer_size:
+ msg = "integer cannot be represented";
+ break;
+ default:
+ msg = boost::archive::archive_exception::what();
+ assert(false);
+ break;
+ }
+ return msg;
+ }
+};
+
+/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////8
+// "Portable" input binary archive. It addresses integer size and endienness so
+// that binary archives can be passed across systems. Note:floating point types
+// not addressed here
+class portable_binary_iarchive :
+ public boost::archive::basic_binary_iprimitive<
+ portable_binary_iarchive,
+ std::istream::char_type,
+ std::istream::traits_type
+ >,
+ public boost::archive::detail::common_iarchive<
+ portable_binary_iarchive
+ >
+ {
+ typedef boost::archive::basic_binary_iprimitive<
+ portable_binary_iarchive,
+ std::istream::char_type,
+ std::istream::traits_type
+ > primitive_base_t;
+ typedef boost::archive::detail::common_iarchive<
+ portable_binary_iarchive
+ > archive_base_t;
+#ifndef BOOST_NO_MEMBER_TEMPLATE_FRIENDS
+public:
+#else
+ friend archive_base_t;
+ friend primitive_base_t; // since with override load below
+ friend class boost::archive::detail::interface_iarchive<
+ portable_binary_iarchive
+ >;
+ friend class boost::archive::load_access;
+protected:
+#endif
+ unsigned int m_flags;
+ void load_impl(boost::intmax_t & l, char maxsize);
+
+ // default fall through for any types not specified here
+ template<class T>
+ void load(T & t){
+ boost::intmax_t l;
+ load_impl(l, sizeof(T));
+ // use cast to avoid compile time warning
+ //t = static_cast< T >(l);
+ t = T(l);
+ }
+ void load(boost::serialization::item_version_type & t){
+ boost::intmax_t l;
+ load_impl(l, sizeof(boost::serialization::item_version_type));
+ // use cast to avoid compile time warning
+ t = boost::serialization::item_version_type(l);
+ }
+ void load(boost::archive::version_type & t){
+ boost::intmax_t l;
+ load_impl(l, sizeof(boost::archive::version_type));
+ // use cast to avoid compile time warning
+ t = boost::archive::version_type(l);
+ }
+ void load(boost::archive::class_id_type & t){
+ boost::intmax_t l;
+ load_impl(l, sizeof(boost::archive::class_id_type));
+ // use cast to avoid compile time warning
+ t = boost::archive::class_id_type(static_cast<int>(l));
+ }
+ void load(std::string & t){
+ this->primitive_base_t::load(t);
+ }
+ #ifndef BOOST_NO_STD_WSTRING
+ void load(std::wstring & t){
+ this->primitive_base_t::load(t);
+ }
+ #endif
+ void load(float & t){
+ this->primitive_base_t::load(t);
+ // floats not supported
+ //BOOST_STATIC_ASSERT(false);
+ }
+ void load(double & t){
+ this->primitive_base_t::load(t);
+ // doubles not supported
+ //BOOST_STATIC_ASSERT(false);
+ }
+ void load(char & t){
+ this->primitive_base_t::load(t);
+ }
+ void load(unsigned char & t){
+ this->primitive_base_t::load(t);
+ }
+ typedef boost::archive::detail::common_iarchive<portable_binary_iarchive>
+ detail_common_iarchive;
+ template<class T>
+ void load_override(T & t){
+ this->detail_common_iarchive::load_override(t);
+ }
+ void load_override(boost::archive::class_name_type & t);
+ // binary files don't include the optional information
+ void load_override(boost::archive::class_id_optional_type &){}
+
+ void init(unsigned int flags);
+public:
+ portable_binary_iarchive(std::istream & is, unsigned flags = 0) :
+ primitive_base_t(
+ * is.rdbuf(),
+ 0 != (flags & boost::archive::no_codecvt)
+ ),
+ archive_base_t(flags),
+ m_flags(0)
+ {
+ init(flags);
+ }
+
+ portable_binary_iarchive(
+ std::basic_streambuf<
+ std::istream::char_type,
+ std::istream::traits_type
+ > & bsb,
+ unsigned int flags
+ ) :
+ primitive_base_t(
+ bsb,
+ 0 != (flags & boost::archive::no_codecvt)
+ ),
+ archive_base_t(flags),
+ m_flags(0)
+ {
+ init(flags);
+ }
+};
+
+} }
+
+// required by export in boost version > 1.34
+#ifdef BOOST_SERIALIZATION_REGISTER_ARCHIVE
+ BOOST_SERIALIZATION_REGISTER_ARCHIVE(portable_binary_iarchive)
+#endif
+
+// required by export in boost <= 1.34
+#define BOOST_ARCHIVE_CUSTOM_IARCHIVE_TYPES portable_binary_iarchive
+
+/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////8
+// portable_binary_iarchive.cpp
+
+// (C) Copyright 2002 Robert Ramey - http://www.rrsd.com .
+// Use, modification and distribution is subject to the Boost Software
+// License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
+// http://www.boost.org/LICENSE_1_0.txt)
+
+// See http://www.boost.org for updates, documentation, and revision history.
+
+#include <istream>
+#include <string>
+
+#include <boost/detail/endian.hpp>
+#include <boost/serialization/throw_exception.hpp>
+#include <boost/archive/archive_exception.hpp>
+
+namespace boost { namespace archive {
+
+inline void
+portable_binary_iarchive::load_impl(boost::intmax_t & l, char maxsize){
+ char size;
+ l = 0;
+ this->primitive_base_t::load(size);
+
+ if(0 == size){
+ return;
+ }
+
+ bool negative = (size < 0);
+ if(negative)
+ size = -size;
+
+ if(size > maxsize)
+ boost::serialization::throw_exception(
+ portable_binary_iarchive_exception()
+ );
+
+ char * cptr = reinterpret_cast<char *>(& l);
+ #ifdef BOOST_BIG_ENDIAN
+ cptr += (sizeof(boost::intmax_t) - size);
+ #endif
+ this->primitive_base_t::load_binary(cptr, size);
+
+ #ifdef BOOST_BIG_ENDIAN
+ if(m_flags & endian_little)
+ #else
+ if(m_flags & endian_big)
+ #endif
+ reverse_bytes(size, cptr);
+
+ if(negative)
+ l = -l;
+}
+
+inline void
+portable_binary_iarchive::load_override(
+ boost::archive::class_name_type & t
+){
+ std::string cn;
+ cn.reserve(BOOST_SERIALIZATION_MAX_KEY_SIZE);
+ load_override(cn);
+ if(cn.size() > (BOOST_SERIALIZATION_MAX_KEY_SIZE - 1))
+ boost::serialization::throw_exception(
+ boost::archive::archive_exception(
+ boost::archive::archive_exception::invalid_class_name)
+ );
+ std::memcpy(t, cn.data(), cn.size());
+ // borland tweak
+ t.t[cn.size()] = '\0';
+}
+
+inline void
+portable_binary_iarchive::init(unsigned int flags){
+ if(0 == (flags & boost::archive::no_header)){
+ // read signature in an archive version independent manner
+ std::string file_signature;
+ * this >> file_signature;
+ if(file_signature != boost::archive::BOOST_ARCHIVE_SIGNATURE())
+ boost::serialization::throw_exception(
+ boost::archive::archive_exception(
+ boost::archive::archive_exception::invalid_signature
+ )
+ );
+ // make sure the version of the reading archive library can
+ // support the format of the archive being read
+ boost::archive::library_version_type input_library_version;
+ * this >> input_library_version;
+
+ // extra little .t is to get around borland quirk
+ if(boost::archive::BOOST_ARCHIVE_VERSION() < input_library_version)
+ boost::serialization::throw_exception(
+ boost::archive::archive_exception(
+ boost::archive::archive_exception::unsupported_version
+ )
+ );
+
+ #if BOOST_WORKAROUND(__MWERKS__, BOOST_TESTED_AT(0x3205))
+ this->set_library_version(input_library_version);
+ //#else
+ //#if ! BOOST_WORKAROUND(BOOST_MSVC, <= 1200)
+ //detail::
+ //#endif
+ boost::archive::detail::basic_iarchive::set_library_version(
+ input_library_version
+ );
+ #endif
+ }
+ unsigned char x;
+ load(x);
+ m_flags = x << CHAR_BIT;
+}
+
+} }
+
+namespace boost {
+namespace archive {
+
+namespace detail {
+ template class archive_serializer_map<portable_binary_iarchive>;
+}
+
+template class basic_binary_iprimitive<
+ portable_binary_iarchive,
+ std::istream::char_type,
+ std::istream::traits_type
+> ;
+
+} // namespace archive
+} // namespace boost
+
+#if defined(_MSC_VER)
+#pragma warning( pop )
+#endif
+
+#endif // PORTABLE_BINARY_IARCHIVE_HPP
diff --git a/external/boost/archive/portable_binary_oarchive.hpp b/external/boost/archive/portable_binary_oarchive.hpp new file mode 100644 index 000000000..19027f65a --- /dev/null +++ b/external/boost/archive/portable_binary_oarchive.hpp @@ -0,0 +1,294 @@ +#ifndef PORTABLE_BINARY_OARCHIVE_HPP
+#define PORTABLE_BINARY_OARCHIVE_HPP
+
+// MS compatible compilers support #pragma once
+#if defined(_MSC_VER)
+# pragma once
+#endif
+
+#if defined(_MSC_VER)
+#pragma warning( push )
+#pragma warning( disable : 4244 )
+#endif
+
+/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////8
+// portable_binary_oarchive.hpp
+
+// (C) Copyright 2002 Robert Ramey - http://www.rrsd.com .
+// Use, modification and distribution is subject to the Boost Software
+// License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
+// http://www.boost.org/LICENSE_1_0.txt)
+
+// See http://www.boost.org for updates, documentation, and revision history.
+
+#include <ostream>
+#include <boost/serialization/string.hpp>
+#include <boost/archive/archive_exception.hpp>
+#include <boost/archive/basic_binary_oprimitive.hpp>
+#include <boost/archive/detail/common_oarchive.hpp>
+#include <boost/archive/detail/register_archive.hpp>
+
+#include <boost/archive/portable_binary_archive.hpp>
+#include <boost/archive/impl/basic_binary_oprimitive.ipp>
+
+namespace boost { namespace archive {
+
+/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////8
+// exception to be thrown if integer read from archive doesn't fit
+// variable being loaded
+class portable_binary_oarchive_exception :
+ public boost::archive::archive_exception
+{
+public:
+ typedef enum {
+ invalid_flags
+ } exception_code;
+ portable_binary_oarchive_exception(exception_code c = invalid_flags )
+ {}
+ virtual const char *what( ) const throw( )
+ {
+ const char *msg = "programmer error";
+ switch(code){
+ case invalid_flags:
+ msg = "cannot be both big and little endian";
+ default:
+ boost::archive::archive_exception::what();
+ }
+ return msg;
+ }
+};
+
+/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////8
+// "Portable" output binary archive. This is a variation of the native binary
+// archive. it addresses integer size and endienness so that binary archives can
+// be passed across systems. Note:floating point types not addressed here
+
+class portable_binary_oarchive :
+ public boost::archive::basic_binary_oprimitive<
+ portable_binary_oarchive,
+ std::ostream::char_type,
+ std::ostream::traits_type
+ >,
+ public boost::archive::detail::common_oarchive<
+ portable_binary_oarchive
+ >
+{
+ typedef boost::archive::basic_binary_oprimitive<
+ portable_binary_oarchive,
+ std::ostream::char_type,
+ std::ostream::traits_type
+ > primitive_base_t;
+ typedef boost::archive::detail::common_oarchive<
+ portable_binary_oarchive
+ > archive_base_t;
+#ifndef BOOST_NO_MEMBER_TEMPLATE_FRIENDS
+public:
+#else
+ friend archive_base_t;
+ friend primitive_base_t; // since with override save below
+ friend class boost::archive::detail::interface_oarchive<
+ portable_binary_oarchive
+ >;
+ friend class boost::archive::save_access;
+protected:
+#endif
+ unsigned int m_flags;
+ void save_impl(const boost::intmax_t l, const char maxsize);
+ // add base class to the places considered when matching
+ // save function to a specific set of arguments. Note, this didn't
+ // work on my MSVC 7.0 system so we use the sure-fire method below
+ // using archive_base_t::save;
+
+ // default fall through for any types not specified here
+ template<class T>
+ void save(const T & t){
+ save_impl(t, sizeof(T));
+ }
+ void save(const std::string & t){
+ this->primitive_base_t::save(t);
+ }
+ #ifndef BOOST_NO_STD_WSTRING
+ void save(const std::wstring & t){
+ this->primitive_base_t::save(t);
+ }
+ #endif
+ void save(const float & t){
+ this->primitive_base_t::save(t);
+ // floats not supported
+ //BOOST_STATIC_ASSERT(false);
+ }
+ void save(const double & t){
+ this->primitive_base_t::save(t);
+ // doubles not supported
+ //BOOST_STATIC_ASSERT(false);
+ }
+ void save(const char & t){
+ this->primitive_base_t::save(t);
+ }
+ void save(const unsigned char & t){
+ this->primitive_base_t::save(t);
+ }
+
+ // default processing - kick back to base class. Note the
+ // extra stuff to get it passed borland compilers
+ typedef boost::archive::detail::common_oarchive<portable_binary_oarchive>
+ detail_common_oarchive;
+ template<class T>
+ void save_override(T & t){
+ this->detail_common_oarchive::save_override(t);
+ }
+ // explicitly convert to char * to avoid compile ambiguities
+ void save_override(const boost::archive::class_name_type & t){
+ const std::string s(t);
+ * this << s;
+ }
+ // binary files don't include the optional information
+ void save_override(
+ const boost::archive::class_id_optional_type & /* t */
+ ){}
+
+ void init(unsigned int flags);
+public:
+ portable_binary_oarchive(std::ostream & os, unsigned flags = 0) :
+ primitive_base_t(
+ * os.rdbuf(),
+ 0 != (flags & boost::archive::no_codecvt)
+ ),
+ archive_base_t(flags),
+ m_flags(flags & (endian_big | endian_little))
+ {
+ init(flags);
+ }
+
+ portable_binary_oarchive(
+ std::basic_streambuf<
+ std::ostream::char_type,
+ std::ostream::traits_type
+ > & bsb,
+ unsigned int flags
+ ) :
+ primitive_base_t(
+ bsb,
+ 0 != (flags & boost::archive::no_codecvt)
+ ),
+ archive_base_t(flags),
+ m_flags(0)
+ {
+ init(flags);
+ }
+};
+
+} }
+
+// required by export in boost version > 1.34
+#ifdef BOOST_SERIALIZATION_REGISTER_ARCHIVE
+ BOOST_SERIALIZATION_REGISTER_ARCHIVE(portable_binary_oarchive)
+#endif
+
+// required by export in boost <= 1.34
+#define BOOST_ARCHIVE_CUSTOM_OARCHIVE_TYPES portable_binary_oarchive
+
+/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////8
+// portable_binary_oarchive.cpp
+
+// (C) Copyright 2002-7 Robert Ramey - http://www.rrsd.com .
+// Use, modification and distribution is subject to the Boost Software
+// License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
+// http://www.boost.org/LICENSE_1_0.txt)
+
+// See http://www.boost.org for updates, documentation, and revision history.
+
+#include <ostream>
+#include <boost/detail/endian.hpp>
+
+namespace boost { namespace archive {
+
+inline void
+portable_binary_oarchive::save_impl(
+ const boost::intmax_t l,
+ const char maxsize
+){
+ char size = 0;
+
+ if(l == 0){
+ this->primitive_base_t::save(size);
+ return;
+ }
+
+ boost::intmax_t ll;
+ bool negative = (l < 0);
+ if(negative)
+ ll = -l;
+ else
+ ll = l;
+
+ do{
+ ll >>= CHAR_BIT;
+ ++size;
+ }while(ll != 0);
+
+ this->primitive_base_t::save(
+ static_cast<char>(negative ? -size : size)
+ );
+
+ if(negative)
+ ll = -l;
+ else
+ ll = l;
+ char * cptr = reinterpret_cast<char *>(& ll);
+ #ifdef BOOST_BIG_ENDIAN
+ cptr += (sizeof(boost::intmax_t) - size);
+ if(m_flags & endian_little)
+ reverse_bytes(size, cptr);
+ #else
+ if(m_flags & endian_big)
+ reverse_bytes(size, cptr);
+ #endif
+ this->primitive_base_t::save_binary(cptr, size);
+}
+
+inline void
+portable_binary_oarchive::init(unsigned int flags) {
+ if(m_flags == (endian_big | endian_little)){
+ boost::serialization::throw_exception(
+ portable_binary_oarchive_exception()
+ );
+ }
+ if(0 == (flags & boost::archive::no_header)){
+ // write signature in an archive version independent manner
+ const std::string file_signature(
+ boost::archive::BOOST_ARCHIVE_SIGNATURE()
+ );
+ * this << file_signature;
+ // write library version
+ const boost::archive::library_version_type v(
+ boost::archive::BOOST_ARCHIVE_VERSION()
+ );
+ * this << v;
+ }
+ save(static_cast<unsigned char>(m_flags >> CHAR_BIT));
+}
+
+} }
+
+namespace boost {
+namespace archive {
+
+namespace detail {
+ template class archive_serializer_map<portable_binary_oarchive>;
+}
+
+template class basic_binary_oprimitive<
+ portable_binary_oarchive,
+ std::ostream::char_type,
+ std::ostream::traits_type
+> ;
+
+} // namespace archive
+} // namespace boost
+
+#if defined(_MSC_VER)
+#pragma warning( pop )
+#endif
+
+#endif // PORTABLE_BINARY_OARCHIVE_HPP
diff --git a/src/common/boost_serialization_helper.h b/src/common/boost_serialization_helper.h index c640a1705..88dccbde7 100644 --- a/src/common/boost_serialization_helper.h +++ b/src/common/boost_serialization_helper.h @@ -30,8 +30,9 @@ #pragma once -#include <boost/archive/binary_oarchive.hpp> #include <boost/archive/binary_iarchive.hpp> +#include <boost/archive/portable_binary_oarchive.hpp> +#include <boost/archive/portable_binary_iarchive.hpp> namespace tools @@ -53,8 +54,8 @@ namespace tools return false; } - FILE* data_file_file = _fdopen(data_file_descriptor, "wb"); - if (0 == data_file_file) + const std::unique_ptr<FILE, tools::close_file> data_file_file{_fdopen(data_file_descriptor, "wb")}; + if (nullptr == data_file_file) { // Call CloseHandle is not necessary _close(data_file_descriptor); @@ -62,11 +63,10 @@ namespace tools } // HACK: undocumented constructor, this code may not compile - std::ofstream data_file(data_file_file); + std::ofstream data_file(data_file_file.get()); if (data_file.fail()) { // Call CloseHandle and _close are not necessary - fclose(data_file_file); return false; } #else @@ -76,7 +76,7 @@ namespace tools return false; #endif - boost::archive::binary_oarchive a(data_file); + boost::archive::portable_binary_oarchive a(data_file); a << obj; if (data_file.fail()) return false; @@ -85,7 +85,6 @@ namespace tools #if defined(_MSC_VER) // To make sure the file is fully stored on disk ::FlushFileBuffers(data_file_handle); - fclose(data_file_file); #endif return true; @@ -101,9 +100,23 @@ namespace tools data_file.open( file_path, std::ios_base::binary | std::ios_base::in); if(data_file.fail()) return false; - boost::archive::binary_iarchive a(data_file); - - a >> obj; + try + { + // first try reading in portable mode + boost::archive::portable_binary_iarchive a(data_file); + a >> obj; + } + catch(...) + { + // if failed, try reading in unportable mode + boost::filesystem::copy_file(file_path, file_path + ".unportable", boost::filesystem::copy_option::overwrite_if_exists); + data_file.close(); + data_file.open( file_path, std::ios_base::binary | std::ios_base::in); + if(data_file.fail()) + return false; + boost::archive::binary_iarchive a(data_file); + a >> obj; + } return !data_file.fail(); CATCH_ENTRY_L0("unserialize_obj_from_file", false); } diff --git a/src/common/util.cpp b/src/common/util.cpp index a53a9be52..6dec6af2a 100644 --- a/src/common/util.cpp +++ b/src/common/util.cpp @@ -50,6 +50,92 @@ namespace tools { std::function<void(int)> signal_handler::m_handler; + std::unique_ptr<std::FILE, tools::close_file> create_private_file(const std::string& name) + { +#ifdef WIN32 + struct close_handle + { + void operator()(HANDLE handle) const noexcept + { + CloseHandle(handle); + } + }; + + std::unique_ptr<void, close_handle> process = nullptr; + { + HANDLE temp{}; + const bool fail = OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, std::addressof(temp)) == 0; + process.reset(temp); + if (fail) + return nullptr; + } + + DWORD sid_size = 0; + GetTokenInformation(process.get(), TokenOwner, nullptr, 0, std::addressof(sid_size)); + if (GetLastError() != ERROR_INSUFFICIENT_BUFFER) + return nullptr; + + std::unique_ptr<char[]> sid{new char[sid_size]}; + if (!GetTokenInformation(process.get(), TokenOwner, sid.get(), sid_size, std::addressof(sid_size))) + return nullptr; + + const PSID psid = reinterpret_cast<const PTOKEN_OWNER>(sid.get())->Owner; + const DWORD daclSize = + sizeof(ACL) + sizeof(ACCESS_ALLOWED_ACE) + GetLengthSid(psid) - sizeof(DWORD); + + const std::unique_ptr<char[]> dacl{new char[daclSize]}; + if (!InitializeAcl(reinterpret_cast<PACL>(dacl.get()), daclSize, ACL_REVISION)) + return nullptr; + + if (!AddAccessAllowedAce(reinterpret_cast<PACL>(dacl.get()), ACL_REVISION, (READ_CONTROL | FILE_GENERIC_READ | DELETE), psid)) + return nullptr; + + SECURITY_DESCRIPTOR descriptor{}; + if (!InitializeSecurityDescriptor(std::addressof(descriptor), SECURITY_DESCRIPTOR_REVISION)) + return nullptr; + + if (!SetSecurityDescriptorDacl(std::addressof(descriptor), true, reinterpret_cast<PACL>(dacl.get()), false)) + return nullptr; + + SECURITY_ATTRIBUTES attributes{sizeof(SECURITY_ATTRIBUTES), std::addressof(descriptor), false}; + std::unique_ptr<void, close_handle> file{ + CreateFile( + name.c_str(), + GENERIC_WRITE, FILE_SHARE_READ, + std::addressof(attributes), + CREATE_NEW, FILE_ATTRIBUTE_TEMPORARY, + nullptr + ) + }; + if (file) + { + const int fd = _open_osfhandle(reinterpret_cast<intptr_t>(file.get()), 0); + if (0 <= fd) + { + file.release(); + std::FILE* real_file = _fdopen(fd, "w"); + if (!real_file) + { + _close(fd); + } + return {real_file, tools::close_file{}}; + } + } +#else + const int fd = open(name.c_str(), (O_RDWR | O_EXCL | O_CREAT), S_IRUSR); + if (0 <= fd) + { + std::FILE* file = fdopen(fd, "w"); + if (!file) + { + close(fd); + } + return {file, tools::close_file{}}; + } +#endif + return nullptr; + } + #ifdef WIN32 std::string get_windows_version_display_string() { diff --git a/src/common/util.h b/src/common/util.h index 4fcf66b8f..3bb9a053e 100644 --- a/src/common/util.h +++ b/src/common/util.h @@ -30,13 +30,15 @@ #pragma once -#include <mutex> -#include <system_error> -#include <boost/filesystem.hpp> +#include <boost/thread/locks.hpp> +#include <boost/thread/mutex.hpp> +#include <csignal> +#include <cstdio> +#include <functional> +#include <memory> +#include <string> -#include "crypto/crypto.h" #include "crypto/hash.h" -#include "misc_language.h" #include "p2p/p2p_protocol_defs.h" /*! \brief Various Tools @@ -46,6 +48,21 @@ */ namespace tools { + //! Functional class for closing C file handles. + struct close_file + { + void operator()(std::FILE* handle) const noexcept + { + if (handle) + { + std::fclose(handle); + } + } + }; + + //! \return File only readable by owner. nullptr if `filename` exists. + std::unique_ptr<std::FILE, close_file> create_private_file(const std::string& filename); + /*! \brief Returns the default data directory. * * \details Windows < Vista: C:\\Documents and Settings\\Username\\Application Data\\CRYPTONOTE_NAME diff --git a/src/cryptonote_core/account.cpp b/src/cryptonote_core/account.cpp index c3f2b4446..89ad4184c 100644 --- a/src/cryptonote_core/account.cpp +++ b/src/cryptonote_core/account.cpp @@ -28,8 +28,6 @@ // // Parts of this file are originally copyright (c) 2012-2013 The Cryptonote developers -#include <boost/archive/binary_oarchive.hpp> -#include <boost/archive/binary_iarchive.hpp> #include <fstream> #include "include_base_utils.h" diff --git a/src/cryptonote_core/blockchain.cpp b/src/cryptonote_core/blockchain.cpp index 70b2ccc79..a23d51126 100644 --- a/src/cryptonote_core/blockchain.cpp +++ b/src/cryptonote_core/blockchain.cpp @@ -30,8 +30,6 @@ #include <algorithm> #include <cstdio> -#include <boost/archive/binary_oarchive.hpp> -#include <boost/archive/binary_iarchive.hpp> #include <boost/filesystem.hpp> #include "include_base_utils.h" @@ -3880,6 +3878,38 @@ std::map<uint64_t, std::tuple<uint64_t, uint64_t, uint64_t>> Blockchain:: get_ou return m_db->get_output_histogram(amounts, unlocked, recent_cutoff); } +std::list<std::pair<Blockchain::block_extended_info,uint64_t>> Blockchain::get_alternative_chains() const +{ + std::list<std::pair<Blockchain::block_extended_info,uint64_t>> chains; + + for (const auto &i: m_alternative_chains) + { + const crypto::hash &top = i.first; + bool found = false; + for (const auto &j: m_alternative_chains) + { + if (j.second.bl.prev_id == top) + { + found = true; + break; + } + } + if (!found) + { + uint64_t length = 1; + auto h = i.second.bl.prev_id; + blocks_ext_by_hash::const_iterator prev; + while ((prev = m_alternative_chains.find(h)) != m_alternative_chains.end()) + { + h = prev->second.bl.prev_id; + ++length; + } + chains.push_back(std::make_pair(i.second, length)); + } + } + return chains; +} + void Blockchain::cancel() { m_cancel = true; diff --git a/src/cryptonote_core/blockchain.h b/src/cryptonote_core/blockchain.h index 9afc22657..245dc6e73 100644 --- a/src/cryptonote_core/blockchain.h +++ b/src/cryptonote_core/blockchain.h @@ -844,6 +844,13 @@ namespace cryptonote void block_longhash_worker(const uint64_t height, const std::vector<block> &blocks, std::unordered_map<crypto::hash, crypto::hash> &map) const; + /** + * @brief returns a set of known alternate chains + * + * @return a list of chains + */ + std::list<std::pair<block_extended_info,uint64_t>> get_alternative_chains() const; + void cancel(); private: diff --git a/src/cryptonote_core/cryptonote_boost_serialization.h b/src/cryptonote_core/cryptonote_boost_serialization.h index 663ef5070..7423b222a 100644 --- a/src/cryptonote_core/cryptonote_boost_serialization.h +++ b/src/cryptonote_core/cryptonote_boost_serialization.h @@ -38,7 +38,8 @@ #include <boost/foreach.hpp> #include <boost/serialization/is_bitwise_serializable.hpp> #include <boost/archive/binary_iarchive.hpp> -#include <boost/archive/binary_oarchive.hpp> +#include <boost/archive/portable_binary_iarchive.hpp> +#include <boost/archive/portable_binary_oarchive.hpp> #include "cryptonote_basic.h" #include "common/unordered_containers_boost_serialization.h" #include "crypto/crypto.h" @@ -230,7 +231,8 @@ namespace boost // a & x.senderPk; // not serialized, as we do not use it in monero currently } - inline void serializeOutPk(boost::archive::binary_iarchive &a, rct::ctkeyV &outPk_, const boost::serialization::version_type ver) + template <class Archive> + inline typename std::enable_if<Archive::is_loading::value, void>::type serializeOutPk(Archive &a, rct::ctkeyV &outPk_, const boost::serialization::version_type ver) { rct::keyV outPk; a & outPk; @@ -242,7 +244,8 @@ namespace boost } } - inline void serializeOutPk(boost::archive::binary_oarchive &a, rct::ctkeyV &outPk_, const boost::serialization::version_type ver) + template <class Archive> + inline typename std::enable_if<Archive::is_saving::value, void>::type serializeOutPk(Archive &a, rct::ctkeyV &outPk_, const boost::serialization::version_type ver) { rct::keyV outPk(outPk_.size()); for (size_t n = 0; n < outPk_.size(); ++n) diff --git a/src/daemon/command_parser_executor.cpp b/src/daemon/command_parser_executor.cpp index 88b77f76d..f07ef1616 100644 --- a/src/daemon/command_parser_executor.cpp +++ b/src/daemon/command_parser_executor.cpp @@ -482,4 +482,15 @@ bool t_command_parser_executor::print_coinbase_tx_sum(const std::vector<std::str return m_executor.print_coinbase_tx_sum(height, count); } +bool t_command_parser_executor::alt_chain_info(const std::vector<std::string>& args) +{ + if(args.size()) + { + std::cout << "No parameters allowed" << std::endl; + return false; + } + + return m_executor.alt_chain_info(); +} + } // namespace daemonize diff --git a/src/daemon/command_parser_executor.h b/src/daemon/command_parser_executor.h index 93b1fab56..cc929db00 100644 --- a/src/daemon/command_parser_executor.h +++ b/src/daemon/command_parser_executor.h @@ -119,6 +119,8 @@ public: bool output_histogram(const std::vector<std::string>& args); bool print_coinbase_tx_sum(const std::vector<std::string>& args); + + bool alt_chain_info(const std::vector<std::string>& args); }; } // namespace daemonize diff --git a/src/daemon/command_server.cpp b/src/daemon/command_server.cpp index 729b19cbf..88c49d111 100644 --- a/src/daemon/command_server.cpp +++ b/src/daemon/command_server.cpp @@ -225,6 +225,11 @@ t_command_server::t_command_server( , std::bind(&t_command_parser_executor::print_coinbase_tx_sum, &m_parser, p::_1) , "Print sum of coinbase transactions (start height, block count)" ); + m_command_lookup.set_handler( + "alt_chain_info" + , std::bind(&t_command_parser_executor::alt_chain_info, &m_parser, p::_1) + , "Print information about alternative chains" + ); } bool t_command_server::process_command_str(const std::string& cmd) diff --git a/src/daemon/rpc_command_executor.cpp b/src/daemon/rpc_command_executor.cpp index 65b42cc47..41b1fad24 100644 --- a/src/daemon/rpc_command_executor.cpp +++ b/src/daemon/rpc_command_executor.cpp @@ -1367,5 +1367,38 @@ bool t_rpc_command_executor::print_coinbase_tx_sum(uint64_t height, uint64_t cou return true; } +bool t_rpc_command_executor::alt_chain_info() +{ + cryptonote::COMMAND_RPC_GET_ALTERNATE_CHAINS::request req; + cryptonote::COMMAND_RPC_GET_ALTERNATE_CHAINS::response res; + epee::json_rpc::error error_resp; + + std::string fail_message = "Unsuccessful"; + + if (m_is_rpc) + { + if (!m_rpc_client->json_rpc_request(req, res, "get_alternate_chains", fail_message.c_str())) + { + return true; + } + } + else + { + if (!m_rpc_server->on_get_alternate_chains(req, res, error_resp)) + { + tools::fail_msg_writer() << fail_message.c_str(); + return true; + } + } + + tools::msg_writer() << boost::lexical_cast<std::string>(res.chains.size()) << " alternate chains found:"; + for (const auto chain: res.chains) + { + tools::msg_writer() << chain.length << " blocks long, branching at height " << (chain.height - chain.length + 1) + << ", difficulty " << chain.difficulty << ": " << chain.block_hash; + } + return true; +} + }// namespace daemonize diff --git a/src/daemon/rpc_command_executor.h b/src/daemon/rpc_command_executor.h index c1c99155b..a6c712c04 100644 --- a/src/daemon/rpc_command_executor.h +++ b/src/daemon/rpc_command_executor.h @@ -137,6 +137,8 @@ public: bool output_histogram(uint64_t min_count, uint64_t max_count); bool print_coinbase_tx_sum(uint64_t height, uint64_t count); + + bool alt_chain_info(); }; } // namespace daemonize diff --git a/src/p2p/net_node.inl b/src/p2p/net_node.inl index 442c42517..f32e7a435 100644 --- a/src/p2p/net_node.inl +++ b/src/p2p/net_node.inl @@ -137,14 +137,34 @@ namespace nodetool { try { - boost::archive::binary_iarchive a(p2p_data); + // first try reading in portable mode + boost::archive::portable_binary_iarchive a(p2p_data); a >> *this; } - catch (const std::exception &e) + catch (...) { - LOG_ERROR("Failed to load p2p config file, falling back to default config"); - m_peerlist = peerlist_manager(); // it was probably half clobbered by the failed load - make_default_config(); + // if failed, try reading in unportable mode + boost::filesystem::copy_file(state_file_path, state_file_path + ".unportable", boost::filesystem::copy_option::overwrite_if_exists); + p2p_data.close(); + p2p_data.open( state_file_path , std::ios_base::binary | std::ios_base::in); + if(!p2p_data.fail()) + { + try + { + boost::archive::binary_iarchive a(p2p_data); + a >> *this; + } + catch (const std::exception &e) + { + LOG_ERROR("Failed to load p2p config file, falling back to default config"); + m_peerlist = peerlist_manager(); // it was probably half clobbered by the failed load + make_default_config(); + } + } + else + { + make_default_config(); + } } }else { @@ -645,7 +665,7 @@ namespace nodetool return false; }; - boost::archive::binary_oarchive a(p2p_data); + boost::archive::portable_binary_oarchive a(p2p_data); a << *this; return true; CATCH_ENTRY_L0("blockchain_storage::save", false); diff --git a/src/p2p/net_peerlist.h b/src/p2p/net_peerlist.h index c19ecf65f..fa69abd6e 100644 --- a/src/p2p/net_peerlist.h +++ b/src/p2p/net_peerlist.h @@ -36,8 +36,9 @@ #include <boost/foreach.hpp> //#include <boost/bimap.hpp> //#include <boost/bimap/multiset_of.hpp> -#include <boost/archive/binary_oarchive.hpp> #include <boost/archive/binary_iarchive.hpp> +#include <boost/archive/portable_binary_oarchive.hpp> +#include <boost/archive/portable_binary_iarchive.hpp> #include <boost/serialization/version.hpp> #include <boost/multi_index_container.hpp> diff --git a/src/ringct/rctSigs.cpp b/src/ringct/rctSigs.cpp index c7f9b6879..4f8782cdf 100644 --- a/src/ringct/rctSigs.cpp +++ b/src/ringct/rctSigs.cpp @@ -40,22 +40,6 @@ using namespace crypto; using namespace std; namespace rct { - namespace { - struct verRangeWrapper_ { - void operator()(const key & C, const rangeSig & as, bool &result) const { - result = verRange(C, as); - } - }; - constexpr const verRangeWrapper_ verRangeWrapper{}; - - struct verRctMGSimpleWrapper_ { - void operator()(const key &message, const mgSig &mg, const ctkeyV & pubs, const key & C, bool &result) const { - result = verRctMGSimple(message, mg, pubs, C); - } - }; - constexpr const verRctMGSimpleWrapper_ verRctMGSimpleWrapper{}; - } - //Borromean (c.f. gmax/andytoshi's paper) boroSig genBorromean(const key64 x, const key64 P1, const key64 P2, const bits indices) { key64 L[2], alpha; diff --git a/src/rpc/core_rpc_server.cpp b/src/rpc/core_rpc_server.cpp index 5bf500733..c2ff63fc7 100644 --- a/src/rpc/core_rpc_server.cpp +++ b/src/rpc/core_rpc_server.cpp @@ -1337,6 +1337,24 @@ namespace cryptonote return true; } //------------------------------------------------------------------------------------------------------------------------------ + bool core_rpc_server::on_get_alternate_chains(const COMMAND_RPC_GET_ALTERNATE_CHAINS::request& req, COMMAND_RPC_GET_ALTERNATE_CHAINS::response& res, epee::json_rpc::error& error_resp) + { + try + { + std::list<std::pair<Blockchain::block_extended_info, uint64_t>> chains = m_core.get_blockchain_storage().get_alternative_chains(); + for (const auto &i: chains) + { + res.chains.push_back(COMMAND_RPC_GET_ALTERNATE_CHAINS::chain_info{epee::string_tools::pod_to_hex(get_block_hash(i.first.bl)), i.first.height, i.second, i.first.cumulative_difficulty}); + } + res.status = CORE_RPC_STATUS_OK; + } + catch (...) + { + res.status = "Error retrieving alternate chains"; + } + return true; + } + //------------------------------------------------------------------------------------------------------------------------------ bool core_rpc_server::on_out_peers(const COMMAND_RPC_OUT_PEERS::request& req, COMMAND_RPC_OUT_PEERS::response& res) { // TODO diff --git a/src/rpc/core_rpc_server.h b/src/rpc/core_rpc_server.h index b7f6cdd60..0c0668f3b 100644 --- a/src/rpc/core_rpc_server.h +++ b/src/rpc/core_rpc_server.h @@ -118,6 +118,7 @@ namespace cryptonote MAP_JON_RPC_WE("get_version", on_get_version, COMMAND_RPC_GET_VERSION) MAP_JON_RPC_WE("get_coinbase_tx_sum", on_get_coinbase_tx_sum, COMMAND_RPC_GET_COINBASE_TX_SUM) MAP_JON_RPC_WE("get_fee_estimate", on_get_per_kb_fee_estimate, COMMAND_RPC_GET_PER_KB_FEE_ESTIMATE) + MAP_JON_RPC_WE_IF("get_alternate_chains",on_get_alternate_chains, COMMAND_RPC_GET_ALTERNATE_CHAINS, !m_restricted) END_JSON_RPC_MAP() END_URI_MAP2() @@ -166,6 +167,7 @@ namespace cryptonote bool on_get_version(const COMMAND_RPC_GET_VERSION::request& req, COMMAND_RPC_GET_VERSION::response& res, epee::json_rpc::error& error_resp); bool on_get_coinbase_tx_sum(const COMMAND_RPC_GET_COINBASE_TX_SUM::request& req, COMMAND_RPC_GET_COINBASE_TX_SUM::response& res, epee::json_rpc::error& error_resp); bool on_get_per_kb_fee_estimate(const COMMAND_RPC_GET_PER_KB_FEE_ESTIMATE::request& req, COMMAND_RPC_GET_PER_KB_FEE_ESTIMATE::response& res, epee::json_rpc::error& error_resp); + bool on_get_alternate_chains(const COMMAND_RPC_GET_ALTERNATE_CHAINS::request& req, COMMAND_RPC_GET_ALTERNATE_CHAINS::response& res, epee::json_rpc::error& error_resp); //----------------------- private: diff --git a/src/rpc/core_rpc_server_commands_defs.h b/src/rpc/core_rpc_server_commands_defs.h index 23fcb0a92..b09cad235 100644 --- a/src/rpc/core_rpc_server_commands_defs.h +++ b/src/rpc/core_rpc_server_commands_defs.h @@ -1336,4 +1336,39 @@ namespace cryptonote END_KV_SERIALIZE_MAP() }; }; + + struct COMMAND_RPC_GET_ALTERNATE_CHAINS + { + struct request + { + BEGIN_KV_SERIALIZE_MAP() + END_KV_SERIALIZE_MAP() + }; + + struct chain_info + { + std::string block_hash; + uint64_t height; + uint64_t length; + uint64_t difficulty; + + BEGIN_KV_SERIALIZE_MAP() + KV_SERIALIZE(block_hash) + KV_SERIALIZE(height) + KV_SERIALIZE(length) + KV_SERIALIZE(difficulty) + END_KV_SERIALIZE_MAP() + }; + + struct response + { + std::string status; + std::list<chain_info> chains; + + BEGIN_KV_SERIALIZE_MAP() + KV_SERIALIZE(status) + KV_SERIALIZE(chains) + END_KV_SERIALIZE_MAP() + }; + }; } diff --git a/src/simplewallet/simplewallet.cpp b/src/simplewallet/simplewallet.cpp index b46447975..1f6afe2db 100644 --- a/src/simplewallet/simplewallet.cpp +++ b/src/simplewallet/simplewallet.cpp @@ -335,7 +335,6 @@ bool simple_wallet::seed(const std::vector<std::string> &args/* = std::vector<st bool simple_wallet::seed_set_language(const std::vector<std::string> &args/* = std::vector<std::string>()*/) { - bool success = false; if (m_wallet->watch_only()) { fail_msg_writer() << tr("wallet is watch-only and has no seed"); @@ -347,87 +346,49 @@ bool simple_wallet::seed_set_language(const std::vector<std::string> &args/* = s return true; } - tools::password_container pwd_container(m_wallet_file.empty()); - success = pwd_container.read_password(); - if (!success) + const auto pwd_container = get_and_verify_password(); + if (pwd_container) { - fail_msg_writer() << tr("failed to read wallet password"); - return true; - } + std::string mnemonic_language = get_mnemonic_language(); + if (mnemonic_language.empty()) + return true; - /* verify password before using so user doesn't accidentally set a new password for rewritten wallet */ - success = m_wallet->verify_password(pwd_container.password()); - if (!success) - { - fail_msg_writer() << tr("invalid password"); - return true; + m_wallet->set_seed_language(std::move(mnemonic_language)); + m_wallet->rewrite(m_wallet_file, pwd_container->password()); } - - std::string mnemonic_language = get_mnemonic_language(); - if (mnemonic_language.empty()) - return true; - m_wallet->set_seed_language(mnemonic_language); - m_wallet->rewrite(m_wallet_file, pwd_container.password()); return true; } bool simple_wallet::set_always_confirm_transfers(const std::vector<std::string> &args/* = std::vector<std::string>()*/) { - bool success = false; - tools::password_container pwd_container(m_wallet_file.empty()); - success = pwd_container.read_password(); - if (!success) + const auto pwd_container = get_and_verify_password(); + if (pwd_container) { - fail_msg_writer() << tr("failed to read wallet password"); - return true; - } - - /* verify password before using so user doesn't accidentally set a new password for rewritten wallet */ - success = m_wallet->verify_password(pwd_container.password()); - if (!success) - { - fail_msg_writer() << tr("invalid password"); - return true; + m_wallet->always_confirm_transfers(is_it_true(args[1])); + m_wallet->rewrite(m_wallet_file, pwd_container->password()); } - - m_wallet->always_confirm_transfers(is_it_true(args[1])); - m_wallet->rewrite(m_wallet_file, pwd_container.password()); return true; } bool simple_wallet::set_store_tx_info(const std::vector<std::string> &args/* = std::vector<std::string>()*/) { - bool success = false; if (m_wallet->watch_only()) { fail_msg_writer() << tr("wallet is watch-only and cannot transfer"); return true; } - tools::password_container pwd_container(m_wallet_file.empty()); - success = pwd_container.read_password(); - if (!success) + const auto pwd_container = get_and_verify_password(); + if (pwd_container) { - fail_msg_writer() << tr("failed to read wallet password"); - return true; + m_wallet->store_tx_info(is_it_true(args[1])); + m_wallet->rewrite(m_wallet_file, pwd_container->password()); } - - /* verify password before using so user doesn't accidentally set a new password for rewritten wallet */ - success = m_wallet->verify_password(pwd_container.password()); - if (!success) - { - fail_msg_writer() << tr("invalid password"); - return true; - } - - m_wallet->store_tx_info(is_it_true(args[1])); - m_wallet->rewrite(m_wallet_file, pwd_container.password()); return true; } bool simple_wallet::set_default_mixin(const std::vector<std::string> &args/* = std::vector<std::string>()*/) { - bool success = false; if (m_wallet->watch_only()) { fail_msg_writer() << tr("wallet is watch-only and cannot transfer"); @@ -449,25 +410,12 @@ bool simple_wallet::set_default_mixin(const std::vector<std::string> &args/* = s if (mixin == 0) mixin = DEFAULT_MIX; - tools::password_container pwd_container(m_wallet_file.empty()); - - success = pwd_container.read_password(); - if (!success) + const auto pwd_container = get_and_verify_password(); + if (pwd_container) { - fail_msg_writer() << tr("failed to read wallet password"); - return true; + m_wallet->default_mixin(mixin); + m_wallet->rewrite(m_wallet_file, pwd_container->password()); } - - /* verify password before using so user doesn't accidentally set a new password for rewritten wallet */ - success = m_wallet->verify_password(pwd_container.password()); - if (!success) - { - fail_msg_writer() << tr("invalid password"); - return true; - } - - m_wallet->default_mixin(mixin); - m_wallet->rewrite(m_wallet_file, pwd_container.password()); return true; } catch(const boost::bad_lexical_cast &) @@ -484,7 +432,6 @@ bool simple_wallet::set_default_mixin(const std::vector<std::string> &args/* = s bool simple_wallet::set_default_priority(const std::vector<std::string> &args/* = std::vector<std::string>()*/) { - bool success = false; int priority = 0; if (m_wallet->watch_only()) { @@ -512,24 +459,12 @@ bool simple_wallet::set_default_priority(const std::vector<std::string> &args/* } } - tools::password_container pwd_container(m_wallet_file.empty()); - success = pwd_container.read_password(); - if (!success) + const auto pwd_container = get_and_verify_password(); + if (pwd_container) { - fail_msg_writer() << tr("failed to read wallet password"); - return true; - } - - /* verify password before using so user doesn't accidentally set a new password for rewritten wallet */ - success = m_wallet->verify_password(pwd_container.password()); - if (!success) - { - fail_msg_writer() << tr("invalid password"); - return true; + m_wallet->set_default_priority(priority); + m_wallet->rewrite(m_wallet_file, pwd_container->password()); } - - m_wallet->set_default_priority(priority); - m_wallet->rewrite(m_wallet_file, pwd_container.password()); return true; } catch(const boost::bad_lexical_cast &) @@ -546,93 +481,52 @@ bool simple_wallet::set_default_priority(const std::vector<std::string> &args/* bool simple_wallet::set_auto_refresh(const std::vector<std::string> &args/* = std::vector<std::string>()*/) { - - tools::password_container pwd_container(m_wallet_file.empty()); - - bool success = pwd_container.read_password(); - if (!success) + const auto pwd_container = get_and_verify_password(); + if (pwd_container) { - fail_msg_writer() << tr("failed to read wallet password"); - return true; - } + const bool auto_refresh = is_it_true(args[1]); + m_wallet->auto_refresh(auto_refresh); + m_idle_mutex.lock(); + m_auto_refresh_enabled.store(auto_refresh, std::memory_order_relaxed); + m_idle_cond.notify_one(); + m_idle_mutex.unlock(); - /* verify password before using so user doesn't accidentally set a new password for rewritten wallet */ - success = m_wallet->verify_password(pwd_container.password()); - if (!success) - { - fail_msg_writer() << tr("invalid password"); - return true; + m_wallet->rewrite(m_wallet_file, pwd_container->password()); } - - bool auto_refresh = is_it_true(args[1]); - m_wallet->auto_refresh(auto_refresh); - m_idle_mutex.lock(); - m_auto_refresh_enabled.store(auto_refresh, std::memory_order_relaxed); - m_idle_cond.notify_one(); - m_idle_mutex.unlock(); - - m_wallet->rewrite(m_wallet_file, pwd_container.password()); return true; } bool simple_wallet::set_refresh_type(const std::vector<std::string> &args/* = std::vector<std::string>()*/) { - bool success = false; - tools::wallet2::RefreshType refresh_type; if (!parse_refresh_type(args[1], refresh_type)) { return true; } - tools::password_container pwd_container(m_wallet_file.empty()); - success = pwd_container.read_password(); - if (!success) - { - fail_msg_writer() << tr("failed to read wallet password"); - return true; - } - - /* verify password before using so user doesn't accidentally set a new password for rewritten wallet */ - success = m_wallet->verify_password(pwd_container.password()); - if (!success) + const auto pwd_container = get_and_verify_password(); + if (pwd_container) { - fail_msg_writer() << tr("invalid password"); - return true; + m_wallet->set_refresh_type(refresh_type); + m_wallet->rewrite(m_wallet_file, pwd_container->password()); } - - m_wallet->set_refresh_type(refresh_type); - - m_wallet->rewrite(m_wallet_file, pwd_container.password()); return true; } bool simple_wallet::set_confirm_missing_payment_id(const std::vector<std::string> &args/* = std::vector<std::string>()*/) { - bool success = false; if (m_wallet->watch_only()) { fail_msg_writer() << tr("wallet is watch-only and cannot transfer"); return true; } - tools::password_container pwd_container(m_wallet_file.empty()); - success = pwd_container.read_password(); - if (!success) - { - fail_msg_writer() << tr("failed to read wallet password"); - return true; - } - /* verify password before using so user doesn't accidentally set a new password for rewritten wallet */ - success = m_wallet->verify_password(pwd_container.password()); - if (!success) + const auto pwd_container = get_and_verify_password(); + if (pwd_container) { - fail_msg_writer() << tr("invalid password"); - return true; + m_wallet->confirm_missing_payment_id(is_it_true(args[1])); + m_wallet->rewrite(m_wallet_file, pwd_container->password()); } - - m_wallet->confirm_missing_payment_id(is_it_true(args[1])); - m_wallet->rewrite(m_wallet_file, pwd_container.password()); return true; } @@ -678,7 +572,7 @@ simple_wallet::simple_wallet() m_cmd_binder.set_handler("rescan_spent", boost::bind(&simple_wallet::rescan_spent, this, _1), tr("Rescan blockchain for spent outputs")); m_cmd_binder.set_handler("get_tx_key", boost::bind(&simple_wallet::get_tx_key, this, _1), tr("Get transaction key (r) for a given <txid>")); m_cmd_binder.set_handler("check_tx_key", boost::bind(&simple_wallet::check_tx_key, this, _1), tr("Check amount going to <address> in <txid>")); - m_cmd_binder.set_handler("show_transfers", boost::bind(&simple_wallet::show_transfers, this, _1), tr("show_transfers [in|out] [<min_height> [<max_height>]] - Show incoming/outgoing transfers within an optional height range")); + m_cmd_binder.set_handler("show_transfers", boost::bind(&simple_wallet::show_transfers, this, _1), tr("show_transfers [in|out|pending|failed|pool] [<min_height> [<max_height>]] - Show incoming/outgoing transfers within an optional height range")); m_cmd_binder.set_handler("rescan_bc", boost::bind(&simple_wallet::rescan_blockchain, this, _1), tr("Rescan blockchain from scratch")); m_cmd_binder.set_handler("set_tx_note", boost::bind(&simple_wallet::set_tx_note, this, _1), tr("Set an arbitrary string note for a txid")); m_cmd_binder.set_handler("get_tx_note", boost::bind(&simple_wallet::get_tx_note, this, _1), tr("Get a string note for a txid")); @@ -1298,7 +1192,20 @@ std::string simple_wallet::get_mnemonic_language() } return language_list[language_number]; } +//---------------------------------------------------------------------------------------------------- +boost::optional<tools::password_container> simple_wallet::get_and_verify_password() const +{ + auto pwd_container = tools::wallet2::password_prompt(m_wallet_file.empty()); + if (!pwd_container) + return boost::none; + if (!m_wallet->verify_password(pwd_container->password())) + { + fail_msg_writer() << tr("invalid password"); + return boost::none; + } + return pwd_container; +} //---------------------------------------------------------------------------------------------------- bool simple_wallet::new_wallet(const boost::program_options::variables_map& vm, const crypto::secret_key& recovery_key, bool recover, bool two_random, const std::string &old_language) @@ -1532,29 +1439,15 @@ bool simple_wallet::save(const std::vector<std::string> &args) //---------------------------------------------------------------------------------------------------- bool simple_wallet::save_watch_only(const std::vector<std::string> &args/* = std::vector<std::string>()*/) { - bool success = false; - tools::password_container pwd_container(m_wallet_file.empty()); + const auto pwd_container = tools::password_container::prompt(true, tr("Password for new watch-only wallet")); - success = pwd_container.read_password(tr("Password for the new watch-only wallet")); - if (!success) - { - fail_msg_writer() << tr("failed to read wallet password"); - return true; - } - std::string password = pwd_container.password(); - success = pwd_container.read_password(tr("Enter new password again")); - if (!success) + if (!pwd_container) { fail_msg_writer() << tr("failed to read wallet password"); return true; } - if (password != pwd_container.password()) - { - fail_msg_writer() << tr("passwords do not match"); - return true; - } - m_wallet->write_watch_only_wallet(m_wallet_file, pwd_container.password()); + m_wallet->write_watch_only_wallet(m_wallet_file, pwd_container->password()); return true; } @@ -2836,7 +2729,8 @@ bool simple_wallet::donate(const std::vector<std::string> &args_) return true; } std::string mixin_str; - std::string address_str = "donate.getmonero.org"; + // Hardcode Monero's donation address (see #1447) + const std::string address_str = "44AFFq5kSiGBoZ4NMDwYtN18obc8AemS33DBLWs3H7otXft3XjrpDtQGv7SqSsaBYBb98uNbr2VBBEt7f2wfn3RVGQBEP3A"; std::string amount_str; std::string payment_id_str; // check payment id @@ -2864,6 +2758,7 @@ bool simple_wallet::donate(const std::vector<std::string> &args_) if (!payment_id_str.empty()) local_args.push_back(payment_id_str); transfer_new(local_args); + return true; } //---------------------------------------------------------------------------------------------------- bool simple_wallet::accept_loaded_tx(const std::function<size_t()> get_num_txes, const std::function<const tools::wallet2::tx_construction_data&(size_t)> &get_tx, const std::string &extra_message) @@ -3882,7 +3777,7 @@ bool simple_wallet::export_outputs(const std::vector<std::string> &args) std::vector<tools::wallet2::transfer_details> outs = m_wallet->export_outputs(); std::stringstream oss; - boost::archive::binary_oarchive ar(oss); + boost::archive::portable_binary_oarchive ar(oss); ar << outs; std::string magic(OUTPUT_EXPORT_FILE_MAGIC, strlen(OUTPUT_EXPORT_FILE_MAGIC)); @@ -3962,10 +3857,19 @@ bool simple_wallet::import_outputs(const std::vector<std::string> &args) std::string body(data, headerlen); std::stringstream iss; iss << body; - boost::archive::binary_iarchive ar(iss); std::vector<tools::wallet2::transfer_details> outputs; - ar >> outputs; - + try + { + boost::archive::portable_binary_iarchive ar(iss); + ar >> outputs; + } + catch (...) + { + iss.str(""); + iss << body; + boost::archive::binary_iarchive ar(iss); + ar >> outputs; + } size_t n_outputs = m_wallet->import_outputs(outputs); success_msg_writer() << boost::lexical_cast<std::string>(n_outputs) << " outputs imported"; } diff --git a/src/simplewallet/simplewallet.h b/src/simplewallet/simplewallet.h index 420597699..c3e14a8cc 100644 --- a/src/simplewallet/simplewallet.h +++ b/src/simplewallet/simplewallet.h @@ -81,6 +81,9 @@ namespace cryptonote void wallet_idle_thread(); + //! \return Prompts user for password and verifies against local file. Logs on error and returns `none` + boost::optional<tools::password_container> get_and_verify_password() const; + bool new_wallet(const boost::program_options::variables_map& vm, const crypto::secret_key& recovery_key, bool recover, bool two_random, const std::string &old_language); bool new_wallet(const boost::program_options::variables_map& vm, const cryptonote::account_public_address& address, diff --git a/src/wallet/api/wallet_manager.cpp b/src/wallet/api/wallet_manager.cpp index 5a6f02b01..4ee5ab8df 100644 --- a/src/wallet/api/wallet_manager.cpp +++ b/src/wallet/api/wallet_manager.cpp @@ -352,6 +352,14 @@ double WalletManagerImpl::miningHashRate() const return mres.speed; } +std::string WalletManagerImpl::resolveOpenAlias(const std::string &address, bool &dnssec_valid) const +{ + std::vector<std::string> addresses = tools::wallet2::addresses_from_url(address, dnssec_valid); + if (addresses.empty()) + return ""; + return addresses.front(); +} + ///////////////////// WalletManagerFactory implementation ////////////////////// WalletManager *WalletManagerFactory::getWalletManager() diff --git a/src/wallet/api/wallet_manager.h b/src/wallet/api/wallet_manager.h index fe9662534..214afc3fa 100644 --- a/src/wallet/api/wallet_manager.h +++ b/src/wallet/api/wallet_manager.h @@ -52,6 +52,7 @@ public: uint64_t blockchainTargetHeight() const; uint64_t networkDifficulty() const; double miningHashRate() const; + std::string resolveOpenAlias(const std::string &address, bool &dnssec_valid) const; private: WalletManagerImpl() {} diff --git a/src/wallet/password_container.cpp b/src/wallet/password_container.cpp index 5260bbc8b..832b93a1a 100644 --- a/src/wallet/password_container.cpp +++ b/src/wallet/password_container.cpp @@ -42,153 +42,17 @@ #include <unistd.h> #endif -namespace tools +namespace { - namespace - { - bool is_cin_tty(); - } - // deleted via private member - password_container::password_container() - : m_empty(true),m_verify(true) - { - - } - password_container::password_container(bool verify) - : m_empty(true),m_verify(verify) - { - - } - - password_container::password_container(std::string&& password) - : m_empty(false) - , m_password(std::move(password)) - , m_verify(false) - { - - } - - - password_container::password_container(password_container&& rhs) - : m_empty(std::move(rhs.m_empty)) - , m_password(std::move(rhs.m_password)) - , m_verify(std::move(rhs.m_verify)) - { - } - password_container::~password_container() - { - clear(); - } - - void password_container::clear() - { - if (0 < m_password.capacity()) - { - m_password.replace(0, m_password.capacity(), m_password.capacity(), '\0'); - m_password.resize(0); - } - m_empty = true; - } - - bool password_container::read_password(const char *message) - { - clear(); - - bool r; - if (is_cin_tty()) - { - r = read_from_tty_double_check(message); - } - else - { - r = read_from_file(); - } - - if (r) - { - m_empty = false; - } - else - { - clear(); - } - - return r; - } - - bool password_container::read_from_file() - { - m_password.reserve(max_password_size); - for (size_t i = 0; i < max_password_size; ++i) - { - char ch = static_cast<char>(std::cin.get()); - if (std::cin.eof() || ch == '\n' || ch == '\r') - { - break; - } - else if (std::cin.fail()) - { - return false; - } - else - { - m_password.push_back(ch); - } - } - - return true; - } - -bool password_container::read_from_tty_double_check(const char *message) { - std::string pass1; - std::string pass2; - bool match=false; - bool doNotVerifyEntry=false; - if (m_verify){message = "Enter a password for your new wallet";} - do{ - if (message) - std::cout << message <<": "; - if (!password_container::read_from_tty(pass1)) - return false; - if (m_verify==true){//double check password; - std::cout << "Confirm Password: "; - if (!password_container::read_from_tty(pass2)) - return false; - if(pass1!=pass2){ //new password entered did not match - - std::cout << "Passwords do not match! Please try again." << std::endl; - pass1=""; - pass2=""; - match=false; - } - else{//new password matches - match=true; - } - } - else - doNotVerifyEntry=true; //do not verify - //No need to verify password entered at this point in the code - - }while(match==false && doNotVerifyEntry==false); - - m_password=pass1; - return true; - } - - #if defined(_WIN32) - - namespace + bool is_cin_tty() noexcept { - bool is_cin_tty() - { - return 0 != _isatty(_fileno(stdin)); - } + return 0 != _isatty(_fileno(stdin)); } - bool password_container::read_from_tty(std::string & pass) + bool read_from_tty(std::string& pass) { - const char BACKSPACE = 8; + static constexpr const char BACKSPACE = 8; HANDLE h_cin = ::GetStdHandle(STD_INPUT_HANDLE); @@ -198,8 +62,8 @@ bool password_container::read_from_tty_double_check(const char *message) { ::SetConsoleMode(h_cin, mode_new); bool r = true; - pass.reserve(max_password_size); - while (pass.size() < max_password_size) + pass.reserve(tools::password_container::max_password_size); + while (pass.size() < tools::password_container::max_password_size) { DWORD read; char ch; @@ -235,38 +99,36 @@ bool password_container::read_from_tty_double_check(const char *message) { return r; } -#else +#else // end WIN32 - namespace + bool is_cin_tty() noexcept { - bool is_cin_tty() - { - return 0 != isatty(fileno(stdin)); - } + return 0 != isatty(fileno(stdin)); + } - int getch() - { - struct termios tty_old; - tcgetattr(STDIN_FILENO, &tty_old); + int getch() noexcept + { + struct termios tty_old; + tcgetattr(STDIN_FILENO, &tty_old); - struct termios tty_new; - tty_new = tty_old; - tty_new.c_lflag &= ~(ICANON | ECHO); - tcsetattr(STDIN_FILENO, TCSANOW, &tty_new); + struct termios tty_new; + tty_new = tty_old; + tty_new.c_lflag &= ~(ICANON | ECHO); + tcsetattr(STDIN_FILENO, TCSANOW, &tty_new); - int ch = getchar(); + int ch = getchar(); - tcsetattr(STDIN_FILENO, TCSANOW, &tty_old); + tcsetattr(STDIN_FILENO, TCSANOW, &tty_old); - return ch; - } + return ch; } - bool password_container::read_from_tty(std::string &aPass) + + bool read_from_tty(std::string& aPass) { - const char BACKSPACE = 127; + static constexpr const char BACKSPACE = 127; - aPass.reserve(max_password_size); - while (aPass.size() < max_password_size) + aPass.reserve(tools::password_container::max_password_size); + while (aPass.size() < tools::password_container::max_password_size) { int ch = getch(); if (EOF == ch) @@ -297,5 +159,90 @@ bool password_container::read_from_tty_double_check(const char *message) { return true; } -#endif -} +#endif // end !WIN32 + + void clear(std::string& pass) noexcept + { + //! TODO Call a memory wipe function that hopefully is not optimized out + pass.replace(0, pass.capacity(), pass.capacity(), '\0'); + pass.clear(); + } + + bool read_from_tty(const bool verify, const char *message, std::string& pass1, std::string& pass2) + { + while (true) + { + if (message) + std::cout << message <<": "; + if (!read_from_tty(pass1)) + return false; + if (verify) + { + std::cout << "Confirm Password: "; + if (!read_from_tty(pass2)) + return false; + if(pass1!=pass2) + { + std::cout << "Passwords do not match! Please try again." << std::endl; + clear(pass1); + clear(pass2); + } + else //new password matches + return true; + } + else + return true; + //No need to verify password entered at this point in the code + } + + return false; + } + + bool read_from_file(std::string& pass) + { + pass.reserve(tools::password_container::max_password_size); + for (size_t i = 0; i < tools::password_container::max_password_size; ++i) + { + char ch = static_cast<char>(std::cin.get()); + if (std::cin.eof() || ch == '\n' || ch == '\r') + { + break; + } + else if (std::cin.fail()) + { + return false; + } + else + { + pass.push_back(ch); + } + } + return true; + } + +} // anonymous namespace + +namespace tools +{ + // deleted via private member + password_container::password_container() noexcept : m_password() {} + password_container::password_container(std::string&& password) noexcept + : m_password(std::move(password)) + { + } + + password_container::~password_container() noexcept + { + clear(m_password); + } + + boost::optional<password_container> password_container::prompt(const bool verify, const char *message) + { + password_container pass1{}; + password_container pass2{}; + if (is_cin_tty() ? read_from_tty(verify, message, pass1.m_password, pass2.m_password) : read_from_file(pass1.m_password)) + return {std::move(pass1)}; + + return boost::none; + } +} diff --git a/src/wallet/password_container.h b/src/wallet/password_container.h index 866d170f2..9c6faf9c8 100644 --- a/src/wallet/password_container.h +++ b/src/wallet/password_container.h @@ -31,34 +31,37 @@ #pragma once #include <string> -#include <boost/program_options/variables_map.hpp> +#include <boost/optional/optional.hpp> namespace tools { class password_container { public: - static const size_t max_password_size = 1024; - password_container(bool verify); - password_container(password_container&& rhs); - password_container(std::string&& password); - ~password_container(); + static constexpr const size_t max_password_size = 1024; - void clear(); - bool empty() const { return m_empty; } - const std::string& password() const { return m_password; } - void password(std::string&& val) { m_password = std::move(val); m_empty = false; } - bool read_password(const char *message = "Password"); + //! Empty password + password_container() noexcept; - private: - //delete constructor with no parameters - password_container(); - bool read_from_file(); - bool read_from_tty(std::string & pass); - bool read_from_tty_double_check(const char *message); + //! `password` is used as password + password_container(std::string&& password) noexcept; + + //! \return A password from stdin TTY prompt or `std::cin` pipe. + static boost::optional<password_container> prompt(bool verify, const char *mesage = "Password"); + + password_container(const password_container&) = delete; + password_container(password_container&& rhs) = default; + + //! Wipes internal password + ~password_container() noexcept; - bool m_empty; + password_container& operator=(const password_container&) = delete; + password_container& operator=(password_container&&) = default; + + const std::string& password() const noexcept { return m_password; } + + private: + //! TODO Custom allocator that locks to RAM? std::string m_password; - bool m_verify; }; } diff --git a/src/wallet/wallet2.cpp b/src/wallet/wallet2.cpp index de41acb2d..221dd8e0b 100644 --- a/src/wallet/wallet2.cpp +++ b/src/wallet/wallet2.cpp @@ -30,8 +30,6 @@ #include <random> #include <tuple> -#include <boost/archive/binary_oarchive.hpp> -#include <boost/archive/binary_iarchive.hpp> #include <boost/format.hpp> #include <boost/optional/optional.hpp> #include <boost/utility/value_init.hpp> @@ -174,9 +172,7 @@ boost::optional<tools::password_container> get_password(const boost::program_opt if (command_line::has_arg(vm, opts.password)) { - tools::password_container pwd(false); - pwd.password(command_line::get_arg(vm, opts.password)); - return {std::move(pwd)}; + return tools::password_container{command_line::get_arg(vm, opts.password)}; } if (command_line::has_arg(vm, opts.password_file)) @@ -192,19 +188,10 @@ boost::optional<tools::password_container> get_password(const boost::program_opt // Remove line breaks the user might have inserted boost::trim_right_if(password, boost::is_any_of("\r\n")); - return {tools::password_container(std::move(password))}; + return {tools::password_container{std::move(password)}}; } - //vm is already part of the password container class. just need to check vm for an already existing wallet - //here need to pass in variable map. This will indicate if the wallet already exists to the read password function - tools::password_container pwd(verify); - if (pwd.read_password()) - { - return {std::move(pwd)}; - } - - tools::fail_msg_writer() << tools::wallet2::tr("failed to read wallet password"); - return boost::none; + return tools::wallet2::password_prompt(verify); } std::unique_ptr<tools::wallet2> generate_from_json(const std::string& json_file, bool testnet, bool restricted) @@ -431,6 +418,18 @@ void wallet2::init_options(boost::program_options::options_description& desc_par command_line::add_arg(desc_params, opts.restricted); } +boost::optional<password_container> wallet2::password_prompt(const bool is_new_wallet) +{ + auto pwd_container = tools::password_container::prompt( + is_new_wallet, (is_new_wallet ? tr("Enter a password for your new wallet") : tr("Wallet password")) + ); + if (!pwd_container) + { + tools::fail_msg_writer() << tr("failed to read wallet password"); + } + return pwd_container; +} + std::unique_ptr<wallet2> wallet2::make_from_json(const boost::program_options::variables_map& vm, const std::string& json_file) { const options opts{}; @@ -444,7 +443,7 @@ std::pair<std::unique_ptr<wallet2>, password_container> wallet2::make_from_file( auto pwd = get_password(vm, opts, false); if (!pwd) { - return {nullptr, password_container(false)}; + return {nullptr, password_container{}}; } auto wallet = make_basic(vm, opts); if (wallet) @@ -460,7 +459,7 @@ std::pair<std::unique_ptr<wallet2>, password_container> wallet2::make_new(const auto pwd = get_password(vm, opts, true); if (!pwd) { - return {nullptr, password_container(false)}; + return {nullptr, password_container{}}; } return {make_basic(vm, opts), std::move(*pwd)}; } @@ -2313,16 +2312,38 @@ void wallet2::load(const std::string& wallet_, const std::string& password) std::stringstream iss; iss << cache_data; - boost::archive::binary_iarchive ar(iss); - ar >> *this; + try { + boost::archive::portable_binary_iarchive ar(iss); + ar >> *this; + } + catch (...) + { + LOG_PRINT_L0("Failed to open portable binary, trying unportable"); + boost::filesystem::copy_file(m_wallet_file, m_wallet_file + ".unportable", boost::filesystem::copy_option::overwrite_if_exists); + iss.str(""); + iss << cache_data; + boost::archive::binary_iarchive ar(iss); + ar >> *this; + } } catch (...) { LOG_PRINT_L1("Failed to load encrypted cache, trying unencrypted"); std::stringstream iss; iss << buf; - boost::archive::binary_iarchive ar(iss); - ar >> *this; + try { + boost::archive::portable_binary_iarchive ar(iss); + ar >> *this; + } + catch (...) + { + LOG_PRINT_L0("Failed to open portable binary, trying unportable"); + boost::filesystem::copy_file(m_wallet_file, m_wallet_file + ".unportable", boost::filesystem::copy_option::overwrite_if_exists); + iss.str(""); + iss << buf; + boost::archive::binary_iarchive ar(iss); + ar >> *this; + } } THROW_WALLET_EXCEPTION_IF( m_account_public_address.m_spend_public_key != m_account.get_keys().m_account_address.m_spend_public_key || @@ -2396,7 +2417,7 @@ void wallet2::store_to(const std::string &path, const std::string &password) } // preparing wallet data std::stringstream oss; - boost::archive::binary_oarchive ar(oss); + boost::archive::portable_binary_oarchive ar(oss); ar << *this; wallet2::cache_file_data cache_file_data = boost::value_initialized<wallet2::cache_file_data>(); diff --git a/src/wallet/wallet2.h b/src/wallet/wallet2.h index c3381730b..54e26008b 100644 --- a/src/wallet/wallet2.h +++ b/src/wallet/wallet2.h @@ -31,7 +31,6 @@ #pragma once #include <memory> -#include <boost/archive/binary_iarchive.hpp> #include <boost/program_options/options_description.hpp> #include <boost/program_options/variables_map.hpp> @@ -104,6 +103,9 @@ namespace tools static bool has_testnet_option(const boost::program_options::variables_map& vm); static void init_options(boost::program_options::options_description& desc_params); + //! \return Password retrieved from prompt. Logs error on failure. + static boost::optional<password_container> password_prompt(const bool is_new_wallet); + //! Uses stdin and stdout. Returns a wallet2 if no errors. static std::unique_ptr<wallet2> make_from_json(const boost::program_options::variables_map& vm, const std::string& json_file); @@ -676,11 +678,11 @@ namespace boost namespace serialization { template <class Archive> - inline void initialize_transfer_details(Archive &a, tools::wallet2::transfer_details &x, const boost::serialization::version_type ver) + inline typename std::enable_if<!Archive::is_loading::value, void>::type initialize_transfer_details(Archive &a, tools::wallet2::transfer_details &x, const boost::serialization::version_type ver) { } - template<> - inline void initialize_transfer_details(boost::archive::binary_iarchive &a, tools::wallet2::transfer_details &x, const boost::serialization::version_type ver) + template <class Archive> + inline typename std::enable_if<Archive::is_loading::value, void>::type initialize_transfer_details(Archive &a, tools::wallet2::transfer_details &x, const boost::serialization::version_type ver) { if (ver < 1) { diff --git a/src/wallet/wallet2_api.h b/src/wallet/wallet2_api.h index 6651b876d..2e1d95b58 100644 --- a/src/wallet/wallet2_api.h +++ b/src/wallet/wallet2_api.h @@ -561,6 +561,9 @@ struct WalletManager //! returns current mining hash rate (0 if not mining) virtual double miningHashRate() const = 0; + + //! resolves an OpenAlias address to a monero address + virtual std::string resolveOpenAlias(const std::string &address, bool &dnssec_valid) const = 0; }; diff --git a/src/wallet/wallet_rpc_server.cpp b/src/wallet/wallet_rpc_server.cpp index 7c08bbe4b..2a259029d 100644 --- a/src/wallet/wallet_rpc_server.cpp +++ b/src/wallet/wallet_rpc_server.cpp @@ -28,6 +28,7 @@ // // Parts of this file are originally copyright (c) 2012-2013 The Cryptonote developers #include <boost/asio/ip/address.hpp> +#include <boost/filesystem/operations.hpp> #include <cstdint> #include "include_base_utils.h" using namespace epee; @@ -36,10 +37,12 @@ using namespace epee; #include "wallet/wallet_args.h" #include "common/command_line.h" #include "common/i18n.h" +#include "common/util.h" #include "cryptonote_core/cryptonote_format_utils.h" #include "cryptonote_core/account.h" #include "wallet_rpc_server_commands_defs.h" #include "misc_language.h" +#include "string_coding.h" #include "string_tools.h" #include "crypto/hash.h" @@ -47,9 +50,11 @@ namespace { const command_line::arg_descriptor<std::string, true> arg_rpc_bind_port = {"rpc-bind-port", "Sets bind port for server"}; const command_line::arg_descriptor<std::string> arg_rpc_bind_ip = {"rpc-bind-ip", "Specify ip to bind rpc server", "127.0.0.1"}; - const command_line::arg_descriptor<std::string> arg_user_agent = {"user-agent", "Restrict RPC to clients using this user agent", ""}; - + const command_line::arg_descriptor<std::string> arg_rpc_login = {"rpc-login", "Specify username[:password] required for RPC connection"}; + const command_line::arg_descriptor<bool> arg_disable_rpc_login = {"disable-rpc-login", "Disable HTTP authentication for RPC"}; const command_line::arg_descriptor<bool> arg_confirm_external_bind = {"confirm-external-bind", "Confirm rcp-bind-ip value is NOT a loopback (local) IP"}; + + constexpr const char default_rpc_username[] = "monero"; } namespace tools @@ -60,9 +65,19 @@ namespace tools } //------------------------------------------------------------------------------------------------------------------------------ - wallet_rpc_server::wallet_rpc_server(wallet2& w):m_wallet(w) + wallet_rpc_server::wallet_rpc_server(wallet2& w):m_wallet(w), rpc_login_filename(), m_stop(false) {} //------------------------------------------------------------------------------------------------------------------------------ + wallet_rpc_server::~wallet_rpc_server() + { + try + { + boost::system::error_code ec{}; + boost::filesystem::remove(rpc_login_filename, ec); + } + catch (...) {} + } + //------------------------------------------------------------------------------------------------------------------------------ bool wallet_rpc_server::run() { m_stop = false; @@ -110,11 +125,79 @@ namespace tools } } + epee::net_utils::http::http_auth::login login{}; + + const bool disable_auth = command_line::get_arg(vm, arg_disable_rpc_login); + const std::string user_pass = command_line::get_arg(vm, arg_rpc_login); + const std::string bind_port = command_line::get_arg(vm, arg_rpc_bind_port); + + if (disable_auth) + { + if (!user_pass.empty()) + { + LOG_ERROR(tr("Cannot specify --") << arg_disable_rpc_login.name << tr(" and --") << arg_rpc_login.name); + return false; + } + } + else // auth enabled + { + if (user_pass.empty()) + { + login.username = default_rpc_username; + + std::array<std::uint8_t, 16> rand_128bit{{}}; + crypto::rand(rand_128bit.size(), rand_128bit.data()); + login.password = string_encoding::base64_encode(rand_128bit.data(), rand_128bit.size()); + } + else // user password + { + const auto loc = user_pass.find(':'); + login.username = user_pass.substr(0, loc); + if (loc != std::string::npos) + { + login.password = user_pass.substr(loc + 1); + } + else + { + login.password = tools::password_container::prompt(true, "RPC password").value_or( + tools::password_container{} + ).password(); + } + + if (login.username.empty() || login.password.empty()) + { + LOG_ERROR(tr("Blank username or password not permitted for RPC authenticaion")); + return false; + } + } + + assert(!login.username.empty()); + assert(!login.password.empty()); + + std::string temp = "monero-wallet-rpc." + bind_port + ".login"; + const auto cookie = tools::create_private_file(temp); + if (!cookie) + { + LOG_ERROR(tr("Failed to create file ") << temp << tr(". Check permissions or remove file")); + return false; + } + rpc_login_filename.swap(temp); // nothrow guarantee destructor cleanup + temp = rpc_login_filename; + std::fputs(login.username.c_str(), cookie.get()); + std::fputc(':', cookie.get()); + std::fputs(login.password.c_str(), cookie.get()); + std::fflush(cookie.get()); + if (std::ferror(cookie.get())) + { + LOG_ERROR(tr("Error writing to file ") << temp); + return false; + } + LOG_PRINT_L0(tr("RPC username/password is stored in file ") << temp); + } // end auth enabled + m_net_server.set_threads_prefix("RPC"); return epee::http_server_impl_base<wallet_rpc_server, connection_context>::init( - command_line::get_arg(vm, arg_rpc_bind_port), - std::move(bind_ip), - command_line::get_arg(vm, arg_user_agent) + std::move(bind_port), std::move(bind_ip), std::string{}, boost::make_optional(!disable_auth, std::move(login)) ); } //------------------------------------------------------------------------------------------------------------------------------ @@ -1132,7 +1215,8 @@ int main(int argc, char** argv) { tools::wallet2::init_options(desc_params); command_line::add_arg(desc_params, arg_rpc_bind_ip); command_line::add_arg(desc_params, arg_rpc_bind_port); - command_line::add_arg(desc_params, arg_user_agent); + command_line::add_arg(desc_params, arg_rpc_login); + command_line::add_arg(desc_params, arg_disable_rpc_login); command_line::add_arg(desc_params, arg_confirm_external_bind); command_line::add_arg(desc_params, arg_wallet_file); command_line::add_arg(desc_params, arg_from_json); diff --git a/src/wallet/wallet_rpc_server.h b/src/wallet/wallet_rpc_server.h index 96ca1af04..92deec043 100644 --- a/src/wallet/wallet_rpc_server.h +++ b/src/wallet/wallet_rpc_server.h @@ -32,6 +32,7 @@ #include <boost/program_options/options_description.hpp> #include <boost/program_options/variables_map.hpp> +#include <string> #include "net/http_server_impl_base.h" #include "wallet_rpc_server_commands_defs.h" #include "wallet2.h" @@ -48,6 +49,7 @@ namespace tools static const char* tr(const char* str); wallet_rpc_server(wallet2& cr); + ~wallet_rpc_server(); bool init(const boost::program_options::variables_map& vm); bool run(); @@ -112,12 +114,11 @@ namespace tools bool on_make_uri(const wallet_rpc::COMMAND_RPC_MAKE_URI::request& req, wallet_rpc::COMMAND_RPC_MAKE_URI::response& res, epee::json_rpc::error& er); bool on_parse_uri(const wallet_rpc::COMMAND_RPC_PARSE_URI::request& req, wallet_rpc::COMMAND_RPC_PARSE_URI::response& res, epee::json_rpc::error& er); - bool handle_command_line(const boost::program_options::variables_map& vm); - //json rpc v2 bool on_query_key(const wallet_rpc::COMMAND_RPC_QUERY_KEY::request& req, wallet_rpc::COMMAND_RPC_QUERY_KEY::response& res, epee::json_rpc::error& er); wallet2& m_wallet; + std::string rpc_login_filename; std::atomic<bool> m_stop; }; } |