Coverage Report

Created: 2025-08-25 06:28

/src/libtorrent/src/choker.cpp
Line
Count
Source (jump to first uncovered line)
1
/*
2
3
Copyright (c) 2019, Amir Abrams
4
Copyright (c) 2014-2020, Arvid Norberg
5
Copyright (c) 2016, 2018, Alden Torres
6
Copyright (c) 2016, Steven Siloti
7
Copyright (c) 2019, Monson Shao
8
All rights reserved.
9
10
Redistribution and use in source and binary forms, with or without
11
modification, are permitted provided that the following conditions
12
are met:
13
14
    * Redistributions of source code must retain the above copyright
15
      notice, this list of conditions and the following disclaimer.
16
    * Redistributions in binary form must reproduce the above copyright
17
      notice, this list of conditions and the following disclaimer in
18
      the documentation and/or other materials provided with the distribution.
19
    * Neither the name of the author nor the names of its
20
      contributors may be used to endorse or promote products derived
21
      from this software without specific prior written permission.
22
23
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
24
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
27
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
28
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
29
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
30
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
31
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
32
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
33
POSSIBILITY OF SUCH DAMAGE.
34
35
*/
36
37
#include "libtorrent/choker.hpp"
38
#include "libtorrent/peer_connection.hpp"
39
#include "libtorrent/aux_/session_settings.hpp"
40
#include "libtorrent/aux_/time.hpp"
41
#include "libtorrent/torrent.hpp"
42
43
#include <functional>
44
45
using namespace std::placeholders;
46
47
namespace libtorrent {
48
49
namespace {
50
51
  int compare_peers(peer_connection const* lhs, peer_connection const* rhs)
52
0
  {
53
0
    int const prio1 = lhs->get_priority(peer_connection::upload_channel);
54
0
    int const prio2 = rhs->get_priority(peer_connection::upload_channel);
55
56
0
    if (prio1 != prio2) return prio1 > prio2 ? 1 : -1;
57
58
    // compare how many bytes they've sent us
59
0
    std::int64_t const c1 = lhs->downloaded_in_last_round();
60
0
    std::int64_t const c2 = rhs->downloaded_in_last_round();
61
62
0
    if (c1 != c2) return c1 > c2 ? 1 : -1;
63
0
    return 0;
64
0
  }
65
66
  // return true if 'lhs' peer should be preferred to be unchoke over 'rhs'
67
  bool unchoke_compare_rr(peer_connection const* lhs
68
    , peer_connection const* rhs, int pieces)
69
0
  {
70
0
    int const cmp = compare_peers(lhs, rhs);
71
0
    if (cmp != 0) return cmp > 0;
72
73
    // when seeding, rotate which peer is unchoked in a round-robin fashion
74
75
    // the amount uploaded since unchoked (not just in the last round)
76
0
    std::int64_t const u1 = lhs->uploaded_since_unchoked();
77
0
    std::int64_t const u2 = rhs->uploaded_since_unchoked();
78
79
    // the way the round-robin unchoker works is that it,
80
    // by default, prioritizes any peer that is already unchoked.
81
    // this maintain the status quo across unchoke rounds. However,
82
    // peers that are unchoked, but have sent more than one quota
83
    // since they were unchoked, they get de-prioritized.
84
85
0
    std::shared_ptr<torrent> const t1 = lhs->associated_torrent().lock();
86
0
    std::shared_ptr<torrent> const t2 = rhs->associated_torrent().lock();
87
0
    TORRENT_ASSERT(t1);
88
0
    TORRENT_ASSERT(t2);
89
90
    // if a peer is already unchoked, the number of bytes sent since it was unchoked
91
    // is greater than the send quanta, and it has been unchoked for at least one minute
92
    // then it's done with its upload slot, and we can de-prioritize it
93
0
    bool const c1_quota_complete = !lhs->is_choked()
94
0
      && u1 > std::int64_t(t1->torrent_file().piece_length()) * pieces
95
0
      && aux::time_now() - lhs->time_of_last_unchoke() > minutes(1);
96
0
    bool const c2_quota_complete = !rhs->is_choked()
97
0
      && u2 > std::int64_t(t2->torrent_file().piece_length()) * pieces
98
0
      && aux::time_now() - rhs->time_of_last_unchoke() > minutes(1);
99
100
    // if c2 has completed a quanta, it should be de-prioritized
101
    // and vice versa
102
0
    if (c1_quota_complete != c2_quota_complete)
103
0
      return int(c1_quota_complete) < int(c2_quota_complete);
104
105
    // when seeding, prefer the peer we're uploading the fastest to
106
107
    // force the upload rate to zero for choked peers because
108
    // if the peers just got choked the previous round
109
    // there may have been a residual transfer which was already
110
    // in-flight at the time and we don't want that to cause the peer
111
    // to be ranked at the top of the choked peers
112
0
    std::int64_t const c1 = lhs->is_choked() ? 0 : lhs->uploaded_in_last_round();
113
0
    std::int64_t const c2 = rhs->is_choked() ? 0 : rhs->uploaded_in_last_round();
114
115
0
    if (c1 != c2) return c1 > c2;
116
117
    // if the peers are still identical (say, they're both waiting to be unchoked)
118
    // prioritize the one that has waited the longest to be unchoked
119
    // the round-robin unchoker relies on this logic. Don't change it
120
    // without moving this into that unchoker logic
121
0
    return lhs->time_of_last_unchoke() < rhs->time_of_last_unchoke();
122
0
  }
123
124
  // return true if 'lhs' peer should be preferred to be unchoke over 'rhs'
125
  bool unchoke_compare_fastest_upload(peer_connection const* lhs
126
    , peer_connection const* rhs)
127
0
  {
128
0
    int const cmp = compare_peers(lhs, rhs);
129
0
    if (cmp != 0) return cmp > 0;
130
131
    // when seeding, prefer the peer we're uploading the fastest to
132
0
    std::int64_t const c1 = lhs->uploaded_in_last_round();
133
0
    std::int64_t const c2 = rhs->uploaded_in_last_round();
134
135
0
    if (c1 != c2) return c1 > c2;
136
137
    // prioritize the one that has waited the longest to be unchoked
138
    // the round-robin unchoker relies on this logic. Don't change it
139
    // without moving this into that unchoker logic
140
0
    return lhs->time_of_last_unchoke() < rhs->time_of_last_unchoke();
141
0
  }
142
143
  int anti_leech_score(peer_connection const* peer)
144
0
  {
145
    // the anti-leech seeding algorithm is based on the paper "Improving
146
    // BitTorrent: A Simple Approach" from Chow et. al. and ranks peers based
147
    // on how many pieces they have, preferring to unchoke peers that just
148
    // started and peers that are close to completing. Like this:
149
    //   ^
150
    //   | \                       / |
151
    //   |  \                     /  |
152
    //   |   \                   /   |
153
    // s |    \                 /    |
154
    // c |     \               /     |
155
    // o |      \             /      |
156
    // r |       \           /       |
157
    // e |        \         /        |
158
    //   |         \       /         |
159
    //   |          \     /          |
160
    //   |           \   /           |
161
    //   |            \ /            |
162
    //   |             V             |
163
    //   +---------------------------+
164
    //   0%    num have pieces     100%
165
0
    std::shared_ptr<torrent> const t = peer->associated_torrent().lock();
166
0
    TORRENT_ASSERT(t);
167
168
0
    std::int64_t const total_size = t->torrent_file().total_size();
169
0
    if (total_size == 0) return 0;
170
    // Cap the given_size so that it never causes the score to increase
171
0
    std::int64_t const given_size = std::min(peer->statistics().total_payload_upload()
172
0
      , total_size / 2);
173
0
    std::int64_t const have_size = std::max(given_size
174
0
      , std::int64_t(t->torrent_file().piece_length()) * peer->num_have_pieces());
175
0
    return int(std::abs((have_size - total_size / 2) * 2000 / total_size));
176
0
  }
177
178
  // return true if 'lhs' peer should be preferred to be unchoke over 'rhs'
179
  bool unchoke_compare_anti_leech(peer_connection const* lhs
180
    , peer_connection const* rhs)
181
0
  {
182
0
    int const cmp = compare_peers(lhs, rhs);
183
0
    if (cmp != 0) return cmp > 0;
184
185
0
    int const score1 = anti_leech_score(lhs);
186
0
    int const score2 = anti_leech_score(rhs);
187
0
    if (score1 != score2) return score1 > score2;
188
189
    // prioritize the one that has waited the longest to be unchoked
190
    // the round-robin unchoker relies on this logic. Don't change it
191
    // without moving this into that unchoker logic
192
0
    return lhs->time_of_last_unchoke() < rhs->time_of_last_unchoke();
193
0
  }
194
195
  bool upload_rate_compare(peer_connection const* lhs
196
    , peer_connection const* rhs)
197
0
  {
198
    // take torrent priority into account
199
0
    std::int64_t const c1 = lhs->uploaded_in_last_round()
200
0
      * lhs->get_priority(peer_connection::upload_channel);
201
0
    std::int64_t const c2 = rhs->uploaded_in_last_round()
202
0
      * rhs->get_priority(peer_connection::upload_channel);
203
204
0
    return c1 > c2;
205
0
  }
206
207
  } // anonymous namespace
208
209
  int unchoke_sort(std::vector<peer_connection*>& peers
210
    , time_duration const unchoke_interval
211
    , aux::session_settings const& sett)
212
0
  {
213
0
#if TORRENT_USE_ASSERTS
214
0
    for (auto p : peers)
215
0
    {
216
0
      TORRENT_ASSERT(p->self());
217
0
      TORRENT_ASSERT(p->associated_torrent().lock());
218
0
    }
219
0
#endif
220
221
0
    int upload_slots = sett.get_int(settings_pack::unchoke_slots_limit);
222
0
    if (upload_slots < 0)
223
0
      upload_slots = std::numeric_limits<int>::max();
224
225
    // ==== rate-based ====
226
    //
227
    // The rate based unchoker looks at our upload rate to peers, and find
228
    // a balance between number of upload slots and the rate we achieve. The
229
    // intention is to not spread upload bandwidth too thin, but also to not
230
    // unchoke few enough peers to not be able to saturate the up-link.
231
    // this is done by traversing the peers sorted by our upload rate to
232
    // them in decreasing rates. For each peer we increase the threshold by
233
    // 2 kiB/s. The first peer we get to whom we upload slower than
234
    // the threshold, we stop and that's the number of unchoke slots we have.
235
0
    if (sett.get_int(settings_pack::choking_algorithm)
236
0
      == settings_pack::rate_based_choker)
237
0
    {
238
      // first reset the number of unchoke slots, because we'll calculate
239
      // it purely based on the current state of our peers.
240
0
      upload_slots = 0;
241
242
0
      int rate_threshold = sett.get_int(settings_pack::rate_choker_initial_threshold);
243
244
0
      std::sort(peers.begin(), peers.end()
245
0
        , [](peer_connection const* lhs, peer_connection const* rhs)
246
0
        { return upload_rate_compare(lhs, rhs); });
247
248
0
      for (auto const* p : peers)
249
0
      {
250
0
        int const rate = int(p->uploaded_in_last_round()
251
0
          * 1000 / total_milliseconds(unchoke_interval));
252
253
        // always have at least 1 unchoke slot
254
0
        if (rate < rate_threshold) break;
255
256
0
        ++upload_slots;
257
258
        // TODO: make configurable
259
0
        rate_threshold += 2048;
260
0
      }
261
0
      ++upload_slots;
262
0
    }
263
264
    // sorts the peers that are eligible for unchoke by download rate and
265
    // secondary by total upload. The reason for this is, if all torrents are
266
    // being seeded, the download rate will be 0, and the peers we have sent
267
    // the least to should be unchoked
268
269
    // we use partial sort here, because we only care about the top
270
    // upload_slots peers.
271
272
0
    int const slots = std::min(upload_slots, int(peers.size()));
273
274
0
    if (sett.get_int(settings_pack::seed_choking_algorithm)
275
0
      == settings_pack::round_robin)
276
0
    {
277
0
      int const pieces = sett.get_int(settings_pack::seeding_piece_quota);
278
279
0
      std::nth_element(peers.begin(), peers.begin()
280
0
        + slots, peers.end()
281
0
        , [pieces](peer_connection const* lhs, peer_connection const* rhs)
282
0
        { return unchoke_compare_rr(lhs, rhs, pieces); });
283
0
    }
284
0
    else if (sett.get_int(settings_pack::seed_choking_algorithm)
285
0
      == settings_pack::fastest_upload)
286
0
    {
287
0
      std::nth_element(peers.begin(), peers.begin()
288
0
        + slots, peers.end()
289
0
        , [](peer_connection const* lhs, peer_connection const* rhs)
290
0
        { return unchoke_compare_fastest_upload(lhs, rhs); });
291
0
    }
292
0
    else if (sett.get_int(settings_pack::seed_choking_algorithm)
293
0
      == settings_pack::anti_leech)
294
0
    {
295
0
      std::nth_element(peers.begin(), peers.begin()
296
0
        + slots, peers.end()
297
0
        , [](peer_connection const* lhs, peer_connection const* rhs)
298
0
        { return unchoke_compare_anti_leech(lhs, rhs); });
299
0
    }
300
0
    else
301
0
    {
302
0
      int const pieces = sett.get_int(settings_pack::seeding_piece_quota);
303
0
      std::nth_element(peers.begin(), peers.begin()
304
0
        + slots, peers.end()
305
0
        , [pieces](peer_connection const* lhs, peer_connection const* rhs)
306
0
        { return unchoke_compare_rr(lhs, rhs, pieces); } );
307
308
0
      TORRENT_ASSERT_FAIL();
309
0
    }
310
311
0
    return upload_slots;
312
0
  }
313
314
}