diff --git a/doc/i2p.md b/doc/i2p.md index d224787d7..17a6bea2b 100644 --- a/doc/i2p.md +++ b/doc/i2p.md @@ -1,72 +1,87 @@ # I2P support in Bitcoin ABC It is possible to run Bitcoin ABC as an [I2P (Invisible Internet Project)](https://en.wikipedia.org/wiki/I2P) service and connect to such services. This [glossary](https://geti2p.net/en/about/glossary) may be useful to get started with I2P terminology. ## Run Bitcoin ABC with an I2P router (proxy) A running I2P router (proxy) with [SAM](https://geti2p.net/en/docs/api/samv3) enabled is required (there is an [official one](https://geti2p.net) and [a few alternatives](https://en.wikipedia.org/wiki/I2P#Routers)). Notice the IP address and port the SAM proxy is listening to; usually, it is `127.0.0.1:7656`. Once it is up and running with SAM enabled, use the following Bitcoin ABC options: ``` -i2psam= I2P SAM proxy to reach I2P peers and accept I2P connections (default: none) -i2pacceptincoming If set and -i2psam is also set then incoming I2P connections are accepted via the SAM proxy. If this is not set but -i2psam is set then only outgoing connections will be made to the I2P network. Ignored if -i2psam is not set. Listening for incoming I2P connections is done through the SAM proxy, not by binding to a local address and port (default: 1) ``` In a typical situation, this suffices: ``` bitcoind -i2psam=127.0.0.1:7656 ``` The first time Bitcoin ABC connects to the I2P router, its I2P address (and corresponding private key) will be automatically generated and saved in a file named `i2p_private_key` in the Bitcoin ABC data directory. ## Additional configuration options related to I2P You may set the `debug=i2p` config logging option to have additional information in the debug log about your I2P configuration and connections. Run `bitcoin-cli help logging` for more information. It is possible to restrict outgoing connections in the usual way with `onlynet=i2p`. I2P support was added to Bitcoin ABC in version 22.0 (mid 2021) and there may be fewer I2P peers than Tor or IP ones. Therefore, using `onlynet=i2p` alone (without other `onlynet=`) may make a node more susceptible to [Sybil attacks](https://en.bitcoin.it/wiki/Weaknesses#Sybil_attack). Use `bitcoin-cli -addrinfo` to see the number of I2P addresses known to your node. ## I2P related information in Bitcoin ABC There are several ways to see your I2P address in Bitcoin ABC: - in the debug log (grep for `AddLocal`, the I2P address ends in `.b32.i2p`) - in the output of the `getnetworkinfo` RPC in the "localaddresses" section - in the output of `bitcoin-cli -netinfo` peer connections dashboard To see which I2P peers your node is connected to, use `bitcoin-cli -netinfo 4` or the `getpeerinfo` RPC (e.g. `bitcoin-cli getpeerinfo`). To see which I2P addresses your node knows, use the `getnodeaddresses 0 i2p` RPC. ## Compatibility Bitcoin ABC uses the [SAM v3.1](https://geti2p.net/en/docs/api/samv3) protocol to connect to the I2P network. Any I2P router that supports it can be used. + +## Ports in I2P and Bitcoin ABC + +Bitcoin ABC uses the [SAM v3.1](https://geti2p.net/en/docs/api/samv3) +protocol. One particularity of SAM v3.1 is that it does not support ports, +unlike newer versions of SAM (v3.2 and up) that do support them and default the +port numbers to 0. From the point of view of peers that use newer versions of +SAM or other protocols that support ports, a SAM v3.1 peer is connecting to them +on port 0, from source port 0. + +To allow future upgrades to newer versions of SAM, Bitcoin ABC sets its +listening port to 0 when listening for incoming I2P connections and advertises +its own I2P address with port 0. Furthermore, it will not attempt to connect to +I2P addresses with a non-zero port number because with SAM v3.1 the destination +port (`TO_PORT`) is always set to 0 and is not in the control of Bitcoin ABC. diff --git a/src/chainparams.h b/src/chainparams.h index c287d95c9..f913ea94b 100644 --- a/src/chainparams.h +++ b/src/chainparams.h @@ -1,147 +1,157 @@ // Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2016 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_CHAINPARAMS_H #define BITCOIN_CHAINPARAMS_H #include #include +#include #include #include #include +#include #include struct SeedSpec6 { uint8_t addr[16]; uint16_t port; }; typedef std::map MapCheckpoints; struct CCheckpointData { MapCheckpoints mapCheckpoints; }; /** * Holds various statistics on transactions within a chain. Used to estimate * verification progress during chain sync. * * See also: CChainParams::TxData, GuessVerificationProgress. */ struct ChainTxData { int64_t nTime; int64_t nTxCount; double dTxRate; }; /** * CChainParams defines various tweakable parameters of a given instance of the * Bitcoin system. There are three: the main network on which people trade goods * and services, the public test network which gets reset from time to time and * a regression test mode which is intended for private networks only. It has * minimal difficulty to ensure that blocks can be found instantly. */ class CChainParams { public: enum Base58Type { PUBKEY_ADDRESS, SCRIPT_ADDRESS, SECRET_KEY, EXT_PUBLIC_KEY, EXT_SECRET_KEY, MAX_BASE58_TYPES }; const Consensus::Params &GetConsensus() const { return consensus; } const CMessageHeader::MessageMagic &DiskMagic() const { return diskMagic; } const CMessageHeader::MessageMagic &NetMagic() const { return netMagic; } uint16_t GetDefaultPort() const { return nDefaultPort; } + uint16_t GetDefaultPort(Network net) const { + return net == NET_I2P ? I2P_SAM31_PORT : GetDefaultPort(); + } + uint16_t GetDefaultPort(const std::string &addr) const { + CNetAddr a; + return a.SetSpecial(addr) ? GetDefaultPort(a.GetNetwork()) + : GetDefaultPort(); + } const CBlock &GenesisBlock() const { return genesis; } /** Default value for -checkmempool and -checkblockindex argument */ bool DefaultConsistencyChecks() const { return fDefaultConsistencyChecks; } /** Policy: Filter transactions that do not match well-defined patterns */ bool RequireStandard() const { return fRequireStandard; } /** If this chain is exclusively used for testing */ bool IsTestChain() const { return m_is_test_chain; } /** If this chain allows time to be mocked */ bool IsMockableChain() const { return m_is_mockable_chain; } uint64_t PruneAfterHeight() const { return nPruneAfterHeight; } /** Minimum free space (in GB) needed for data directory */ uint64_t AssumedBlockchainSize() const { return m_assumed_blockchain_size; } /** * Minimum free space (in GB) needed for data directory when pruned; Does * not include prune target */ uint64_t AssumedChainStateSize() const { return m_assumed_chain_state_size; } /** Whether it is possible to mine blocks on demand (no retargeting) */ bool MineBlocksOnDemand() const { return consensus.fPowNoRetargeting; } /** Return the BIP70 network string (main, test or regtest) */ std::string NetworkIDString() const { return strNetworkID; } /** Return the list of hostnames to look up for DNS seeds */ const std::vector &Base58Prefix(Base58Type type) const { return base58Prefixes[type]; } const std::string &CashAddrPrefix() const { return cashaddrPrefix; } const std::vector &FixedSeeds() const { return vFixedSeeds; } const CCheckpointData &Checkpoints() const { return checkpointData; } const ChainTxData &TxData() const { return chainTxData; } protected: CChainParams() {} Consensus::Params consensus; CMessageHeader::MessageMagic diskMagic; CMessageHeader::MessageMagic netMagic; uint16_t nDefaultPort; uint64_t nPruneAfterHeight; uint64_t m_assumed_blockchain_size; uint64_t m_assumed_chain_state_size; std::vector vSeeds; std::vector base58Prefixes[MAX_BASE58_TYPES]; std::string cashaddrPrefix; std::string strNetworkID; CBlock genesis; std::vector vFixedSeeds; bool fDefaultConsistencyChecks; bool fRequireStandard; bool m_is_test_chain; bool m_is_mockable_chain; CCheckpointData checkpointData; ChainTxData chainTxData; friend const std::vector GetRandomizedDNSSeeds(const CChainParams ¶ms); }; /** * Creates and returns a std::unique_ptr of the chosen chain. * @returns a CChainParams* of the chosen chain. * @throws a std::runtime_error if the chain is not supported. */ std::unique_ptr CreateChainParams(const std::string &chain); CBlock CreateGenesisBlock(uint32_t nTime, uint32_t nNonce, uint32_t nBits, int32_t nVersion, const Amount genesisReward); /** * Return the currently selected parameters. This won't change after app * startup, except for unit tests. */ const CChainParams &Params(); /** * Sets the params returned by Params() to those for the given BIP70 chain name. * @throws std::runtime_error when the chain is not supported. */ void SelectParams(const std::string &chain); const CCheckpointData &CheckpointData(const std::string &chain); #endif // BITCOIN_CHAINPARAMS_H diff --git a/src/i2p.cpp b/src/i2p.cpp index 0eecae143..c37851e11 100644 --- a/src/i2p.cpp +++ b/src/i2p.cpp @@ -1,415 +1,421 @@ // Copyright (c) 2020-2020 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace i2p { /** * Swap Standard Base64 <-> I2P Base64. * Standard Base64 uses `+` and `/` as last two characters of its alphabet. * I2P Base64 uses `-` and `~` respectively. * So it is easy to detect in which one is the input and convert to the other. * @param[in] from Input to convert. * @return converted `from` */ static std::string SwapBase64(const std::string &from) { std::string to; to.resize(from.size()); for (size_t i = 0; i < from.size(); ++i) { switch (from[i]) { case '-': to[i] = '+'; break; case '~': to[i] = '/'; break; case '+': to[i] = '-'; break; case '/': to[i] = '~'; break; default: to[i] = from[i]; break; } } return to; } /** * Decode an I2P-style Base64 string. * @param[in] i2p_b64 I2P-style Base64 string. * @return decoded `i2p_b64` * @throw std::runtime_error if decoding fails */ static Binary DecodeI2PBase64(const std::string &i2p_b64) { const std::string &std_b64 = SwapBase64(i2p_b64); bool invalid; Binary decoded = DecodeBase64(std_b64.c_str(), &invalid); if (invalid) { throw std::runtime_error( strprintf("Cannot decode Base64: \"%s\"", i2p_b64)); } return decoded; } /** * Derive the .b32.i2p address of an I2P destination (binary). * @param[in] dest I2P destination. * @return the address that corresponds to `dest` * @throw std::runtime_error if conversion fails */ static CNetAddr DestBinToAddr(const Binary &dest) { CSHA256 hasher; hasher.Write(dest.data(), dest.size()); uint8_t hash[CSHA256::OUTPUT_SIZE]; hasher.Finalize(hash); CNetAddr addr; const std::string addr_str = EncodeBase32(hash, false) + ".b32.i2p"; if (!addr.SetSpecial(addr_str)) { throw std::runtime_error( strprintf("Cannot parse I2P address: \"%s\"", addr_str)); } return addr; } /** * Derive the .b32.i2p address of an I2P destination (I2P-style Base64). * @param[in] dest I2P destination. * @return the address that corresponds to `dest` * @throw std::runtime_error if conversion fails */ static CNetAddr DestB64ToAddr(const std::string &dest) { const Binary &decoded = DecodeI2PBase64(dest); return DestBinToAddr(decoded); } namespace sam { Session::Session(const fs::path &private_key_file, const CService &control_host, CThreadInterrupt *interrupt) : m_private_key_file(private_key_file), m_control_host(control_host), m_interrupt(interrupt), m_control_sock(std::make_unique(INVALID_SOCKET)) {} Session::~Session() { LOCK(m_mutex); Disconnect(); } bool Session::Listen(Connection &conn) { try { LOCK(m_mutex); CreateIfNotCreatedAlready(); conn.me = m_my_addr; conn.sock = StreamAccept(); return true; } catch (const std::runtime_error &e) { Log("Error listening: %s", e.what()); CheckControlSock(); } return false; } bool Session::Accept(Connection &conn) { try { while (!*m_interrupt) { Sock::Event occurred; conn.sock->Wait(MAX_WAIT_FOR_IO, Sock::RECV, &occurred); if ((occurred & Sock::RECV) == 0) { // Timeout, no incoming connections within MAX_WAIT_FOR_IO. continue; } const std::string &peer_dest = conn.sock->RecvUntilTerminator( '\n', MAX_WAIT_FOR_IO, *m_interrupt, MAX_MSG_SIZE); - conn.peer = CService(DestB64ToAddr(peer_dest), - Params().GetDefaultPort()); + conn.peer = CService(DestB64ToAddr(peer_dest), I2P_SAM31_PORT); return true; } } catch (const std::runtime_error &e) { Log("Error accepting: %s", e.what()); CheckControlSock(); } return false; } bool Session::Connect(const CService &to, Connection &conn, bool &proxy_error) { + // Refuse connecting to arbitrary ports. We don't specify any + // destination port to the SAM proxy when connecting (SAM 3.1 does not + // use ports) and it forces/defaults it to I2P_SAM31_PORT. + if (to.GetPort() != I2P_SAM31_PORT) { + proxy_error = false; + return false; + } + proxy_error = true; std::string session_id; std::unique_ptr sock; conn.peer = to; try { { LOCK(m_mutex); CreateIfNotCreatedAlready(); session_id = m_session_id; conn.me = m_my_addr; sock = Hello(); } const Reply &lookup_reply = SendRequestAndGetReply( *sock, strprintf("NAMING LOOKUP NAME=%s", to.ToStringIP())); const std::string &dest = lookup_reply.Get("VALUE"); const Reply &connect_reply = SendRequestAndGetReply( *sock, strprintf("STREAM CONNECT ID=%s DESTINATION=%s SILENT=false", session_id, dest), false); const std::string &result = connect_reply.Get("RESULT"); if (result == "OK") { conn.sock = std::move(sock); return true; } if (result == "INVALID_ID") { LOCK(m_mutex); Disconnect(); throw std::runtime_error("Invalid session id"); } if (result == "CANT_REACH_PEER" || result == "TIMEOUT") { proxy_error = false; } throw std::runtime_error(strprintf("\"%s\"", connect_reply.full)); } catch (const std::runtime_error &e) { Log("Error connecting to %s: %s", to.ToString(), e.what()); CheckControlSock(); return false; } } // Private methods std::string Session::Reply::Get(const std::string &key) const { const auto &pos = keys.find(key); if (pos == keys.end() || !pos->second.has_value()) { throw std::runtime_error( strprintf("Missing %s= in the reply to \"%s\": \"%s\"", key, request, full)); } return pos->second.value(); } template void Session::Log(const std::string &fmt, const Args &... args) const { LogPrint(BCLog::I2P, "I2P: %s\n", tfm::format(fmt, args...)); } Session::Reply Session::SendRequestAndGetReply(const Sock &sock, const std::string &request, bool check_result_ok) const { sock.SendComplete(request + "\n", MAX_WAIT_FOR_IO, *m_interrupt); Reply reply; // Don't log the full "SESSION CREATE ..." because it contains our // private key. reply.request = request.substr(0, 14) == "SESSION CREATE" ? "SESSION CREATE ..." : request; // It could take a few minutes for the I2P router to reply as it is // querying the I2P network (when doing name lookup, for example). // Notice: `RecvUntilTerminator()` is checking `m_interrupt` more often, // so we would not be stuck here for long if `m_interrupt` is signaled. static constexpr auto recv_timeout = 3min; reply.full = sock.RecvUntilTerminator('\n', recv_timeout, *m_interrupt, MAX_MSG_SIZE); for (const auto &kv : spanparsing::Split(reply.full, ' ')) { const auto &pos = std::find(kv.begin(), kv.end(), '='); if (pos != kv.end()) { reply.keys.emplace(std::string{kv.begin(), pos}, std::string{pos + 1, kv.end()}); } else { reply.keys.emplace(std::string{kv.begin(), kv.end()}, std::nullopt); } } if (check_result_ok && reply.Get("RESULT") != "OK") { throw std::runtime_error(strprintf( "Unexpected reply to \"%s\": \"%s\"", request, reply.full)); } return reply; } std::unique_ptr Session::Hello() const { auto sock = CreateSock(m_control_host); if (!sock) { throw std::runtime_error("Cannot create socket"); } if (!ConnectSocketDirectly(m_control_host, *sock, nConnectTimeout, true)) { throw std::runtime_error( strprintf("Cannot connect to %s", m_control_host.ToString())); } SendRequestAndGetReply(*sock, "HELLO VERSION MIN=3.1 MAX=3.1"); return sock; } void Session::CheckControlSock() { LOCK(m_mutex); std::string errmsg; if (!m_control_sock->IsConnected(errmsg)) { Log("Control socket error: %s", errmsg); Disconnect(); } } void Session::DestGenerate(const Sock &sock) { // https://geti2p.net/spec/common-structures#key-certificates // "7" or "EdDSA_SHA512_Ed25519" - "Recent Router Identities and // Destinations". Use "7" because i2pd <2.24.0 does not recognize the // textual form. const Reply &reply = SendRequestAndGetReply( sock, "DEST GENERATE SIGNATURE_TYPE=7", false); m_private_key = DecodeI2PBase64(reply.Get("PRIV")); } void Session::GenerateAndSavePrivateKey(const Sock &sock) { DestGenerate(sock); // umask is set to 077 in init.cpp, which is ok (unless -sysperms is // given) if (!WriteBinaryFile( m_private_key_file, std::string(m_private_key.begin(), m_private_key.end()))) { throw std::runtime_error( strprintf("Cannot save I2P private key to %s", fs::quoted(fs::PathToString(m_private_key_file)))); } } Binary Session::MyDestination() const { // From https://geti2p.net/spec/common-structures#destination: // "They are 387 bytes plus the certificate length specified at bytes // 385-386, which may be non-zero" static constexpr size_t DEST_LEN_BASE = 387; static constexpr size_t CERT_LEN_POS = 385; uint16_t cert_len; memcpy(&cert_len, &m_private_key.at(CERT_LEN_POS), sizeof(cert_len)); cert_len = be16toh(cert_len); const size_t dest_len = DEST_LEN_BASE + cert_len; return Binary{m_private_key.begin(), m_private_key.begin() + dest_len}; } void Session::CreateIfNotCreatedAlready() { std::string errmsg; if (m_control_sock->IsConnected(errmsg)) { return; } Log("Creating SAM session with %s", m_control_host.ToString()); auto sock = Hello(); const auto &[read_ok, data] = ReadBinaryFile(m_private_key_file); if (read_ok) { m_private_key.assign(data.begin(), data.end()); } else { GenerateAndSavePrivateKey(*sock); } const std::string &session_id = GetRandHash().GetHex().substr( 0, 10); // full is an overkill, too verbose in the logs const std::string &private_key_b64 = SwapBase64(EncodeBase64(m_private_key)); SendRequestAndGetReply( *sock, strprintf("SESSION CREATE STYLE=STREAM ID=%s DESTINATION=%s", session_id, private_key_b64)); - m_my_addr = - CService(DestBinToAddr(MyDestination()), Params().GetDefaultPort()); + m_my_addr = CService(DestBinToAddr(MyDestination()), I2P_SAM31_PORT); m_session_id = session_id; m_control_sock = std::move(sock); LogPrintf("I2P: SAM session created: session id=%s, my address=%s\n", m_session_id, m_my_addr.ToString()); } std::unique_ptr Session::StreamAccept() { auto sock = Hello(); const Reply &reply = SendRequestAndGetReply( *sock, strprintf("STREAM ACCEPT ID=%s SILENT=false", m_session_id), false); const std::string &result = reply.Get("RESULT"); if (result == "OK") { return sock; } if (result == "INVALID_ID") { // If our session id is invalid, then force session re-creation on // next usage. Disconnect(); } throw std::runtime_error(strprintf("\"%s\"", reply.full)); } void Session::Disconnect() { if (m_control_sock->Get() != INVALID_SOCKET) { if (m_session_id.empty()) { Log("Destroying incomplete session"); } else { Log("Destroying session %s", m_session_id); } } m_control_sock->Reset(); m_session_id.clear(); } } // namespace sam } // namespace i2p diff --git a/src/init.cpp b/src/init.cpp index 946e6b4b3..5324a706f 100644 --- a/src/init.cpp +++ b/src/init.cpp @@ -1,3186 +1,3187 @@ // Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2018 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #if defined(HAVE_CONFIG_H) #include #endif #include #include #include #include #include #include // For AVALANCHE_LEGACY_PROOF_DEFAULT #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include