• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

lbryio / lbry-sdk / 3788717008

pending completion
3788717008

Pull #3711

github

GitHub
Merge 69297ea9c into 625865165
Pull Request #3711: Bump to Python 3.9 attempt 3.

2802 of 6558 branches covered (42.73%)

Branch coverage included in aggregate %.

25 of 41 new or added lines in 17 files covered. (60.98%)

33 existing lines in 9 files now uncovered.

12281 of 19915 relevant lines covered (61.67%)

1.21 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

74.64
/lbry/extras/daemon/storage.py
1
import os
3✔
2
import logging
3✔
3
import sqlite3
3✔
4
import typing
3✔
5
import asyncio
3✔
6
import binascii
3✔
7
import time
3✔
8
from typing import Optional
3✔
9
from lbry.wallet import SQLiteMixin
3✔
10
from lbry.conf import Config
3✔
11
from lbry.wallet.dewies import dewies_to_lbc, lbc_to_dewies
3✔
12
from lbry.wallet.transaction import Transaction, Output
3✔
13
from lbry.schema.claim import Claim
3✔
14
from lbry.dht.constants import DATA_EXPIRATION
3✔
15
from lbry.blob.blob_info import BlobInfo
3✔
16

17
if typing.TYPE_CHECKING:
3!
18
    from lbry.blob.blob_file import BlobFile
×
19
    from lbry.stream.descriptor import StreamDescriptor
×
20

21
log = logging.getLogger(__name__)
3✔
22

23

24
def calculate_effective_amount(amount: str, supports: typing.Optional[typing.List[typing.Dict]] = None) -> str:
3✔
25
    return dewies_to_lbc(
1✔
26
        lbc_to_dewies(amount) + sum([lbc_to_dewies(support['amount']) for support in supports])
27
    )
28

29

30
class StoredContentClaim:
3✔
31
    def __init__(self, outpoint: Optional[str] = None, claim_id: Optional[str] = None, name: Optional[str] = None,
3✔
32
                 amount: Optional[int] = None, height: Optional[int] = None, serialized: Optional[str] = None,
33
                 channel_claim_id: Optional[str] = None, address: Optional[str] = None,
34
                 claim_sequence: Optional[int] = None, channel_name: Optional[str] = None):
35
        self.claim_id = claim_id
1✔
36
        self.outpoint = outpoint
1✔
37
        self.claim_name = name
1✔
38
        self.amount = amount
1✔
39
        self.height = height
1✔
40
        self.claim: typing.Optional[Claim] = None if not serialized else Claim.from_bytes(
1✔
41
            binascii.unhexlify(serialized)
42
        )
43
        self.claim_address = address
1✔
44
        self.claim_sequence = claim_sequence
1✔
45
        self.channel_claim_id = channel_claim_id
1✔
46
        self.channel_name = channel_name
1✔
47

48
    @property
3✔
49
    def txid(self) -> typing.Optional[str]:
3✔
50
        return None if not self.outpoint else self.outpoint.split(":")[0]
1✔
51

52
    @property
3✔
53
    def nout(self) -> typing.Optional[int]:
3✔
54
        return None if not self.outpoint else int(self.outpoint.split(":")[1])
1✔
55

56
    def as_dict(self) -> typing.Dict:
3✔
57
        return {
1✔
58
            "name": self.claim_name,
59
            "claim_id": self.claim_id,
60
            "address": self.claim_address,
61
            "claim_sequence": self.claim_sequence,
62
            "value": self.claim,
63
            "height": self.height,
64
            "amount": dewies_to_lbc(self.amount),
65
            "nout": self.nout,
66
            "txid": self.txid,
67
            "channel_claim_id": self.channel_claim_id,
68
            "channel_name": self.channel_name
69
        }
70

71

72
def _get_content_claims(transaction: sqlite3.Connection, query: str,
3✔
73
                        source_hashes: typing.List[str]) -> typing.Dict[str, StoredContentClaim]:
74
    claims = {}
1✔
75
    for claim_info in _batched_select(transaction, query, source_hashes):
1✔
76
        claims[claim_info[0]] = StoredContentClaim(*claim_info[1:])
1✔
77
    return claims
1✔
78

79

80
def get_claims_from_stream_hashes(transaction: sqlite3.Connection,
3✔
81
                                  stream_hashes: typing.List[str]) -> typing.Dict[str, StoredContentClaim]:
82
    query = (
1✔
83
        "select content_claim.stream_hash, c.*, case when c.channel_claim_id is not null then "
84
        "   (select claim_name from claim where claim_id==c.channel_claim_id) "
85
        "   else null end as channel_name "
86
        " from content_claim "
87
        " inner join claim c on c.claim_outpoint=content_claim.claim_outpoint and content_claim.stream_hash in {}"
88
        " order by c.rowid desc"
89
    )
90
    return _get_content_claims(transaction, query, stream_hashes)
1✔
91

92

93
def get_claims_from_torrent_info_hashes(transaction: sqlite3.Connection,
3✔
94
                                        info_hashes: typing.List[str]) -> typing.Dict[str, StoredContentClaim]:
95
    query = (
×
96
        "select content_claim.bt_infohash, c.*, case when c.channel_claim_id is not null then "
97
        "   (select claim_name from claim where claim_id==c.channel_claim_id) "
98
        "   else null end as channel_name "
99
        " from content_claim "
100
        " inner join claim c on c.claim_outpoint=content_claim.claim_outpoint and content_claim.bt_infohash in {}"
101
        " order by c.rowid desc"
102
    )
103
    return _get_content_claims(transaction, query, info_hashes)
×
104

105

106
def _batched_select(transaction, query, parameters, batch_size=900):
3✔
107
    for start_index in range(0, len(parameters), batch_size):
1✔
108
        current_batch = parameters[start_index:start_index+batch_size]
1✔
109
        bind = "({})".format(','.join(['?'] * len(current_batch)))
1✔
110
        yield from transaction.execute(query.format(bind), current_batch)
1✔
111

112

113
def _get_lbry_file_stream_dict(rowid, added_on, stream_hash, file_name, download_dir, data_rate, status,
3✔
114
                               sd_hash, stream_key, stream_name, suggested_file_name, claim, saved_file,
115
                               raw_content_fee, fully_reflected):
116
    return {
1✔
117
        "rowid": rowid,
118
        "added_on": added_on,
119
        "stream_hash": stream_hash,
120
        "file_name": file_name,                      # hex
121
        "download_directory": download_dir,          # hex
122
        "blob_data_rate": data_rate,
123
        "status": status,
124
        "sd_hash": sd_hash,
125
        "key": stream_key,
126
        "stream_name": stream_name,                  # hex
127
        "suggested_file_name": suggested_file_name,  # hex
128
        "claim": claim,
129
        "saved_file": bool(saved_file),
130
        "content_fee": None if not raw_content_fee else Transaction(
131
            binascii.unhexlify(raw_content_fee)
132
        ),
133
        "fully_reflected": fully_reflected
134
    }
135

136

137
def get_all_lbry_files(transaction: sqlite3.Connection) -> typing.List[typing.Dict]:
3✔
138
    files = []
1✔
139
    signed_claims = {}
1✔
140
    for (rowid, stream_hash, _, file_name, download_dir, data_rate, status, saved_file, raw_content_fee,
1✔
141
         added_on, _, sd_hash, stream_key, stream_name, suggested_file_name, *claim_args) in transaction.execute(
142
             "select file.rowid, file.*, stream.*, c.*, "
143
             "  case when (SELECT 1 FROM reflected_stream r WHERE r.sd_hash=stream.sd_hash) "
144
             "      is null then 0 else 1 end as fully_reflected "
145
             "from file inner join stream on file.stream_hash=stream.stream_hash "
146
             "inner join content_claim cc on file.stream_hash=cc.stream_hash "
147
             "inner join claim c on cc.claim_outpoint=c.claim_outpoint "
148
             "order by c.rowid desc").fetchall():
149
        claim_args, fully_reflected = tuple(claim_args[:-1]), claim_args[-1]
1✔
150
        claim = StoredContentClaim(*claim_args)
1✔
151
        if claim.channel_claim_id:
1!
152
            if claim.channel_claim_id not in signed_claims:
×
153
                signed_claims[claim.channel_claim_id] = []
×
154
            signed_claims[claim.channel_claim_id].append(claim)
×
155
        files.append(
1✔
156
            _get_lbry_file_stream_dict(
157
                rowid, added_on, stream_hash, file_name, download_dir, data_rate, status,
158
                sd_hash, stream_key, stream_name, suggested_file_name, claim, saved_file,
159
                raw_content_fee, fully_reflected
160
            )
161
        )
162
    for claim_name, claim_id in _batched_select(
1!
163
            transaction, "select c.claim_name, c.claim_id from claim c where c.claim_id in {}",
164
            tuple(signed_claims.keys())):
165
        for claim in signed_claims[claim_id]:
×
166
            claim.channel_name = claim_name
×
167
    return files
1✔
168

169

170
def store_stream(transaction: sqlite3.Connection, sd_blob: 'BlobFile', descriptor: 'StreamDescriptor'):
3✔
171
    # add all blobs, except the last one, which is empty
172
    transaction.executemany(
1✔
173
        "insert or ignore into blob values (?, ?, ?, ?, ?, ?, ?, ?, ?)",
174
        ((blob.blob_hash, blob.length, 0, 0, "pending", 0, 0, blob.added_on, blob.is_mine)
175
         for blob in (descriptor.blobs[:-1] if len(descriptor.blobs) > 1 else descriptor.blobs) + [sd_blob])
176
    ).fetchall()
177
    # associate the blobs to the stream
178
    transaction.execute("insert or ignore into stream values (?, ?, ?, ?, ?)",
1✔
179
                        (descriptor.stream_hash, sd_blob.blob_hash, descriptor.key,
180
                         binascii.hexlify(descriptor.stream_name.encode()).decode(),
181
                         binascii.hexlify(descriptor.suggested_file_name.encode()).decode())).fetchall()
182
    # add the stream
183
    transaction.executemany(
1✔
184
        "insert or ignore into stream_blob values (?, ?, ?, ?)",
185
        ((descriptor.stream_hash, blob.blob_hash, blob.blob_num, blob.iv)
186
         for blob in descriptor.blobs)
187
    ).fetchall()
188
    # ensure should_announce is set regardless if insert was ignored
189
    transaction.execute(
1✔
190
        "update blob set should_announce=1 where blob_hash in (?)",
191
        (sd_blob.blob_hash,)
192
    ).fetchall()
193

194

195
def delete_stream(transaction: sqlite3.Connection, descriptor: 'StreamDescriptor'):
3✔
196
    blob_hashes = [(blob.blob_hash, ) for blob in descriptor.blobs[:-1]]
1✔
197
    blob_hashes.append((descriptor.sd_hash, ))
1✔
198
    transaction.execute("delete from content_claim where stream_hash=? ", (descriptor.stream_hash,)).fetchall()
1✔
199
    transaction.execute("delete from file where stream_hash=? ", (descriptor.stream_hash,)).fetchall()
1✔
200
    transaction.execute("delete from stream_blob where stream_hash=?", (descriptor.stream_hash,)).fetchall()
1✔
201
    transaction.execute("delete from stream where stream_hash=? ", (descriptor.stream_hash,)).fetchall()
1✔
202
    transaction.executemany("delete from blob where blob_hash=?", blob_hashes).fetchall()
1✔
203

204

205
def delete_torrent(transaction: sqlite3.Connection, bt_infohash: str):
3✔
206
    transaction.execute("delete from content_claim where bt_infohash=?", (bt_infohash, )).fetchall()
×
207
    transaction.execute("delete from torrent_tracker where bt_infohash=?", (bt_infohash,)).fetchall()
×
208
    transaction.execute("delete from torrent_node where bt_infohash=?", (bt_infohash,)).fetchall()
×
209
    transaction.execute("delete from torrent_http_seed where bt_infohash=?", (bt_infohash,)).fetchall()
×
210
    transaction.execute("delete from file where bt_infohash=?", (bt_infohash,)).fetchall()
×
211
    transaction.execute("delete from torrent where bt_infohash=?", (bt_infohash,)).fetchall()
×
212

213

214
def store_file(transaction: sqlite3.Connection, stream_hash: str, file_name: typing.Optional[str],
3✔
215
               download_directory: typing.Optional[str], data_payment_rate: float, status: str,
216
               content_fee: typing.Optional[Transaction], added_on: typing.Optional[int] = None) -> int:
217
    if not file_name and not download_directory:
1✔
218
        encoded_file_name, encoded_download_dir = None, None
1✔
219
    else:
220
        encoded_file_name = binascii.hexlify(file_name.encode()).decode()
1✔
221
        encoded_download_dir = binascii.hexlify(download_directory.encode()).decode()
1✔
222
    time_added = added_on or int(time.time())
1✔
223
    transaction.execute(
1✔
224
        "insert or replace into file values (?, NULL, ?, ?, ?, ?, ?, ?, ?)",
225
        (stream_hash, encoded_file_name, encoded_download_dir, data_payment_rate, status,
226
         1 if (file_name and download_directory and os.path.isfile(os.path.join(download_directory, file_name))) else 0,
227
         None if not content_fee else binascii.hexlify(content_fee.raw).decode(), time_added)
228
    ).fetchall()
229

230
    return transaction.execute("select rowid from file where stream_hash=?", (stream_hash, )).fetchone()[0]
1✔
231

232

233
class SQLiteStorage(SQLiteMixin):
3✔
234
    CREATE_TABLES_QUERY = """
3✔
235
            pragma foreign_keys=on;
236
            pragma journal_mode=WAL;
237

238
            create table if not exists blob (
239
                blob_hash char(96) primary key not null,
240
                blob_length integer not null,
241
                next_announce_time integer not null,
242
                should_announce integer not null default 0,
243
                status text not null,
244
                last_announced_time integer,
245
                single_announce integer,
246
                added_on integer not null,
247
                is_mine integer not null default 0
248
            );
249

250
            create table if not exists stream (
251
                stream_hash char(96) not null primary key,
252
                sd_hash char(96) not null references blob,
253
                stream_key text not null,
254
                stream_name text not null,
255
                suggested_filename text not null
256
            );
257

258
            create table if not exists stream_blob (
259
                stream_hash char(96) not null references stream,
260
                blob_hash char(96) references blob,
261
                position integer not null,
262
                iv char(32) not null,
263
                primary key (stream_hash, blob_hash)
264
            );
265

266
            create table if not exists claim (
267
                claim_outpoint text not null primary key,
268
                claim_id char(40) not null,
269
                claim_name text not null,
270
                amount integer not null,
271
                height integer not null,
272
                serialized_metadata blob not null,
273
                channel_claim_id text,
274
                address text not null,
275
                claim_sequence integer not null
276
            );
277

278
            create table if not exists torrent (
279
                bt_infohash char(20) not null primary key,
280
                tracker text,
281
                length integer not null,
282
                name text not null
283
            );
284

285
            create table if not exists torrent_node ( -- BEP-0005
286
                bt_infohash char(20) not null references torrent,
287
                host text not null,
288
                port integer not null
289
            );
290

291
            create table if not exists torrent_tracker ( -- BEP-0012
292
                bt_infohash char(20) not null references torrent,
293
                tracker text not null
294
            );
295

296
            create table if not exists torrent_http_seed ( -- BEP-0017
297
                bt_infohash char(20) not null references torrent,
298
                http_seed text not null
299
            );
300

301
            create table if not exists file (
302
                stream_hash char(96) references stream,
303
                bt_infohash char(20) references torrent,
304
                file_name text,
305
                download_directory text,
306
                blob_data_rate real not null,
307
                status text not null,
308
                saved_file integer not null,
309
                content_fee text,
310
                added_on integer not null
311
            );
312

313
            create table if not exists content_claim (
314
                stream_hash char(96) references stream,
315
                bt_infohash char(20) references torrent,
316
                claim_outpoint text unique not null references claim
317
            );
318

319
            create table if not exists support (
320
                support_outpoint text not null primary key,
321
                claim_id text not null,
322
                amount integer not null,
323
                address text not null
324
            );
325

326
            create table if not exists reflected_stream (
327
                sd_hash text not null,
328
                reflector_address text not null,
329
                timestamp integer,
330
                primary key (sd_hash, reflector_address)
331
            );
332

333
            create table if not exists peer (
334
                node_id char(96) not null primary key,
335
                address text not null,
336
                udp_port integer not null,
337
                tcp_port integer,
338
                unique (address, udp_port)
339
            );
340
            create index if not exists blob_data on blob(blob_hash, blob_length, is_mine);
341
    """
342

343
    def __init__(self, conf: Config, path, loop=None, time_getter: typing.Optional[typing.Callable[[], float]] = None):
3✔
344
        super().__init__(path)
1✔
345
        self.conf = conf
1✔
346
        self.content_claim_callbacks = {}
1✔
347
        self.loop = loop or asyncio.get_event_loop()
1✔
348
        self.time_getter = time_getter or time.time
1✔
349

350
    async def run_and_return_one_or_none(self, query, *args):
3✔
351
        for row in await self.db.execute_fetchall(query, args):
1✔
352
            if len(row) == 1:
1!
353
                return row[0]
1✔
354
            return row
×
355

356
    async def run_and_return_list(self, query, *args):
3✔
357
        rows = list(await self.db.execute_fetchall(query, args))
1✔
358
        return [col[0] for col in rows] if rows else []
1✔
359

360
    # # # # # # # # # blob functions # # # # # # # # #
361

362
    async def add_blobs(self, *blob_hashes_and_lengths: typing.Tuple[str, int, int, int], finished=False):
3✔
363
        def _add_blobs(transaction: sqlite3.Connection):
1✔
364
            transaction.executemany(
1✔
365
                "insert or ignore into blob values (?, ?, ?, ?, ?, ?, ?, ?, ?)",
366
                (
367
                    (blob_hash, length, 0, 0, "pending" if not finished else "finished", 0, 0, added_on, is_mine)
368
                    for blob_hash, length, added_on, is_mine in blob_hashes_and_lengths
369
                )
370
            ).fetchall()
371
            if finished:
1✔
372
                transaction.executemany(
1✔
373
                    "update blob set status='finished' where blob.blob_hash=?", (
374
                        (blob_hash, ) for blob_hash, _, _, _ in blob_hashes_and_lengths
375
                    )
376
                ).fetchall()
377
        return await self.db.run(_add_blobs)
1✔
378

379
    def get_blob_status(self, blob_hash: str):
3✔
380
        return self.run_and_return_one_or_none(
1✔
381
            "select status from blob where blob_hash=?", blob_hash
382
        )
383

384
    def set_announce(self, *blob_hashes):
3✔
385
        return self.db.execute_fetchall(
×
386
            "update blob set should_announce=1 where blob_hash in (?, ?)", blob_hashes
387
        )
388

389
    def update_last_announced_blobs(self, blob_hashes: typing.List[str]):
3✔
390
        def _update_last_announced_blobs(transaction: sqlite3.Connection):
1✔
391
            last_announced = self.time_getter()
1✔
392
            return transaction.executemany(
1✔
393
                "update blob set next_announce_time=?, last_announced_time=?, single_announce=0 "
394
                "where blob_hash=?",
395
                ((int(last_announced + (DATA_EXPIRATION / 2)), int(last_announced), blob_hash)
396
                 for blob_hash in blob_hashes)
397
            ).fetchall()
398
        return self.db.run(_update_last_announced_blobs)
1✔
399

400
    def should_single_announce_blobs(self, blob_hashes, immediate=False):
3✔
401
        def set_single_announce(transaction):
×
402
            now = int(self.time_getter())
×
403
            for blob_hash in blob_hashes:
×
404
                if immediate:
×
405
                    transaction.execute(
×
406
                        "update blob set single_announce=1, next_announce_time=? "
407
                        "where blob_hash=? and status='finished'", (int(now), blob_hash)
408
                    ).fetchall()
409
                else:
410
                    transaction.execute(
×
411
                        "update blob set single_announce=1 where blob_hash=? and status='finished'", (blob_hash,)
412
                    ).fetchall()
413
        return self.db.run(set_single_announce)
×
414

415
    def get_blobs_to_announce(self):
3✔
416
        def get_and_update(transaction):
1✔
417
            timestamp = int(self.time_getter())
1✔
418
            if self.conf.announce_head_and_sd_only:
1!
419
                r = transaction.execute(
1✔
420
                    "select blob_hash from blob "
421
                    "where blob_hash is not null and "
422
                    "(should_announce=1 or single_announce=1) and next_announce_time<? and status='finished' "
423
                    "order by next_announce_time asc limit ?",
424
                    (timestamp, int(self.conf.concurrent_blob_announcers * 10))
425
                ).fetchall()
426
            else:
427
                r = transaction.execute(
×
428
                    "select blob_hash from blob where blob_hash is not null "
429
                    "and next_announce_time<? and status='finished' "
430
                    "order by next_announce_time asc limit ?",
431
                    (timestamp, int(self.conf.concurrent_blob_announcers * 10))
432
                ).fetchall()
433
            return [b[0] for b in r]
1✔
434
        return self.db.run(get_and_update)
1✔
435

436
    def delete_blobs_from_db(self, blob_hashes):
3✔
437
        def delete_blobs(transaction):
1✔
438
            transaction.executemany(
1✔
439
                "delete from blob where blob_hash=?;", ((blob_hash,) for blob_hash in blob_hashes)
440
            ).fetchall()
441
        return self.db.run_with_foreign_keys_disabled(delete_blobs)
1✔
442

443
    def get_all_blob_hashes(self):
3✔
444
        return self.run_and_return_list("select blob_hash from blob")
1✔
445

446
    async def get_stored_blobs(self, is_mine: bool, is_network_blob=False):
3✔
447
        is_mine = 1 if is_mine else 0
×
448
        if is_network_blob:
×
449
            return await self.db.execute_fetchall(
×
450
                "select blob.blob_hash, blob.blob_length, blob.added_on "
451
                "from blob left join stream_blob using (blob_hash) "
452
                "where stream_blob.stream_hash is null and blob.is_mine=? and blob.status='finished'"
453
                "order by blob.blob_length desc, blob.added_on asc",
454
                (is_mine,)
455
            )
456

457
        sd_blobs = await self.db.execute_fetchall(
×
458
            "select blob.blob_hash, blob.blob_length, blob.added_on "
459
            "from blob join stream on blob.blob_hash=stream.sd_hash join file using (stream_hash) "
460
            "where blob.is_mine=? order by blob.added_on asc",
461
            (is_mine,)
462
        )
463
        content_blobs = await self.db.execute_fetchall(
×
464
            "select blob.blob_hash, blob.blob_length, blob.added_on "
465
            "from blob join stream_blob using (blob_hash) cross join stream using (stream_hash)"
466
            "cross join file using (stream_hash)"
467
            "where blob.is_mine=? and blob.status='finished' order by blob.added_on asc, blob.blob_length asc",
468
            (is_mine,)
469
        )
470
        return content_blobs + sd_blobs
×
471

472
    async def get_stored_blob_disk_usage(self):
3✔
473
        total, network_size, content_size, private_size = await self.db.execute_fetchone("""
×
474
        select coalesce(sum(blob_length), 0) as total,
475
               coalesce(sum(case when
476
                   stream_blob.stream_hash is null
477
               then blob_length else 0 end), 0) as network_storage,
478
               coalesce(sum(case when
479
                   stream_blob.blob_hash is not null and is_mine=0
480
               then blob_length else 0 end), 0) as content_storage,
481
               coalesce(sum(case when
482
                   is_mine=1
483
               then blob_length else 0 end), 0) as private_storage
484
        from blob left join stream_blob using (blob_hash)
485
        where blob_hash not in (select sd_hash from stream) and blob.status="finished"
486
        """)
487
        return {
×
488
            'network_storage': network_size,
489
            'content_storage': content_size,
490
            'private_storage': private_size,
491
            'total': total
492
        }
493

494
    async def update_blob_ownership(self, sd_hash, is_mine: bool):
3✔
495
        is_mine = 1 if is_mine else 0
×
496
        await self.db.execute_fetchall(
×
497
            "update blob set is_mine = ? where blob_hash in ("
498
            "   select blob_hash from blob natural join stream_blob natural join stream where sd_hash = ?"
499
            ") OR blob_hash = ?", (is_mine, sd_hash, sd_hash)
500
        )
501

502
    def sync_missing_blobs(self, blob_files: typing.Set[str]) -> typing.Awaitable[typing.Set[str]]:
3✔
503
        def _sync_blobs(transaction: sqlite3.Connection) -> typing.Set[str]:
1✔
504
            finished_blob_hashes = tuple(
1✔
505
                blob_hash for (blob_hash, ) in transaction.execute(
506
                    "select blob_hash from blob where status='finished'"
507
                ).fetchall()
508
            )
509
            finished_blobs_set = set(finished_blob_hashes)
1✔
510
            to_update_set = finished_blobs_set.difference(blob_files)
1✔
511
            transaction.executemany(
1✔
512
                "update blob set status='pending' where blob_hash=?",
513
                ((blob_hash, ) for blob_hash in to_update_set)
514
            ).fetchall()
515
            return blob_files.intersection(finished_blobs_set)
1✔
516
        return self.db.run(_sync_blobs)
1✔
517

518
    # # # # # # # # # stream functions # # # # # # # # #
519

520
    async def stream_exists(self, sd_hash: str) -> bool:
3✔
521
        streams = await self.run_and_return_one_or_none("select stream_hash from stream where sd_hash=?", sd_hash)
1✔
522
        return streams is not None
1✔
523

524
    async def file_exists(self, sd_hash: str) -> bool:
3✔
525
        streams = await self.run_and_return_one_or_none("select f.stream_hash from file f "
1✔
526
                                                        "inner join stream s on "
527
                                                        "s.stream_hash=f.stream_hash and s.sd_hash=?", sd_hash)
528
        return streams is not None
1✔
529

530
    def store_stream(self, sd_blob: 'BlobFile', descriptor: 'StreamDescriptor'):
3✔
531
        return self.db.run(store_stream, sd_blob, descriptor)
1✔
532

533
    def get_blobs_for_stream(self, stream_hash, only_completed=False) -> typing.Awaitable[typing.List[BlobInfo]]:
3✔
534
        def _get_blobs_for_stream(transaction):
1✔
535
            crypt_blob_infos = []
1✔
536
            stream_blobs = transaction.execute(
1✔
537
                "select s.blob_hash, s.position, s.iv, b.added_on "
538
                "from stream_blob s left outer join blob b on b.blob_hash=s.blob_hash where stream_hash=? "
539
                "order by position asc", (stream_hash, )
540
            ).fetchall()
541
            if only_completed:
1!
542
                lengths = transaction.execute(
×
543
                    "select b.blob_hash, b.blob_length from blob b "
544
                    "inner join stream_blob s ON b.blob_hash=s.blob_hash and b.status='finished' and s.stream_hash=?",
545
                    (stream_hash, )
546
                ).fetchall()
547
            else:
548
                lengths = transaction.execute(
1✔
549
                    "select b.blob_hash, b.blob_length from blob b "
550
                    "inner join stream_blob s ON b.blob_hash=s.blob_hash and s.stream_hash=?",
551
                    (stream_hash, )
552
                ).fetchall()
553

554
            blob_length_dict = {}
1✔
555
            for blob_hash, length in lengths:
1✔
556
                blob_length_dict[blob_hash] = length
1✔
557

558
            current_time = time.time()
1✔
559
            for blob_hash, position, iv, added_on in stream_blobs:
1!
560
                blob_length = blob_length_dict.get(blob_hash, 0)
1✔
561
                crypt_blob_infos.append(BlobInfo(position, blob_length, iv, added_on or current_time, blob_hash))
1✔
562
                if not blob_hash:
1✔
563
                    break
1✔
564
            return crypt_blob_infos
1✔
565
        return self.db.run(_get_blobs_for_stream)
1✔
566

567
    def get_sd_blob_hash_for_stream(self, stream_hash):
3✔
568
        return self.run_and_return_one_or_none(
×
569
            "select sd_hash from stream where stream_hash=?", stream_hash
570
        )
571

572
    def get_stream_hash_for_sd_hash(self, sd_blob_hash):
3✔
573
        return self.run_and_return_one_or_none(
×
574
            "select stream_hash from stream where sd_hash = ?", sd_blob_hash
575
        )
576

577
    def delete_stream(self, descriptor: 'StreamDescriptor'):
3✔
578
        return self.db.run_with_foreign_keys_disabled(delete_stream, descriptor)
1✔
579

580
    async def delete_torrent(self, bt_infohash: str):
3✔
581
        return await self.db.run(delete_torrent, bt_infohash)
×
582

583
    # # # # # # # # # file stuff # # # # # # # # #
584

585
    def save_downloaded_file(self, stream_hash: str, file_name: typing.Optional[str],
3✔
586
                             download_directory: typing.Optional[str], data_payment_rate: float,
587
                             content_fee: typing.Optional[Transaction] = None,
588
                             added_on: typing.Optional[int] = None) -> typing.Awaitable[int]:
589
        return self.save_published_file(
1✔
590
            stream_hash, file_name, download_directory, data_payment_rate, status="running",
591
            content_fee=content_fee, added_on=added_on
592
        )
593

594
    def save_published_file(self, stream_hash: str, file_name: typing.Optional[str],
3✔
595
                            download_directory: typing.Optional[str], data_payment_rate: float,
596
                            status: str = "finished",
597
                            content_fee: typing.Optional[Transaction] = None,
598
                            added_on: typing.Optional[int] = None) -> typing.Awaitable[int]:
599
        return self.db.run(store_file, stream_hash, file_name, download_directory, data_payment_rate, status,
1✔
600
                           content_fee, added_on)
601

602
    async def update_manually_removed_files_since_last_run(self):
3✔
603
        """
604
        Update files that have been removed from the downloads directory since the last run
605
        """
606
        def update_manually_removed_files(transaction: sqlite3.Connection):
1✔
607
            files = {}
1✔
608
            query = "select stream_hash, download_directory, file_name from file where saved_file=1 " \
1✔
609
                    "and stream_hash is not null"
610
            for (stream_hash, download_directory, file_name) in transaction.execute(query).fetchall():
1✔
611
                if download_directory and file_name:
1!
612
                    files[stream_hash] = download_directory, file_name
1✔
613
            return files
1✔
614

615
        def detect_removed(files):
1✔
616
            return [
1✔
617
                stream_hash for stream_hash, (download_directory, file_name) in files.items()
618
                if not os.path.isfile(os.path.join(binascii.unhexlify(download_directory).decode(),
619
                                                   binascii.unhexlify(file_name).decode()))
620
            ]
621

622
        def update_db_removed(transaction: sqlite3.Connection, removed):
1✔
623
            query = "update file set file_name=null, download_directory=null, saved_file=0 where stream_hash in {}"
1✔
624
            for cur in _batched_select(transaction, query, removed):
1!
625
                cur.fetchall()
×
626

627
        stream_and_file = await self.db.run(update_manually_removed_files)
1✔
628
        removed = await self.loop.run_in_executor(None, detect_removed, stream_and_file)
1✔
629
        if removed:
1✔
630
            await self.db.run(update_db_removed, removed)
1✔
631

632
    def get_all_lbry_files(self) -> typing.Awaitable[typing.List[typing.Dict]]:
3✔
633
        return self.db.run(get_all_lbry_files)
1✔
634

635
    def change_file_status(self, stream_hash: str, new_status: str):
3✔
636
        log.debug("update file status %s -> %s", stream_hash, new_status)
1✔
637
        return self.db.execute_fetchall("update file set status=? where stream_hash=?", (new_status, stream_hash))
1✔
638

639
    def stop_all_files(self):
3✔
640
        log.debug("stopping all files")
×
641
        return self.db.execute_fetchall("update file set status=?", ("stopped",))
×
642

643
    async def change_file_download_dir_and_file_name(self, stream_hash: str, download_dir: typing.Optional[str],
3✔
644
                                                     file_name: typing.Optional[str]):
645
        if not file_name or not download_dir:
1✔
646
            encoded_file_name, encoded_download_dir = None, None
1✔
647
        else:
648
            encoded_file_name = binascii.hexlify(file_name.encode()).decode()
1✔
649
            encoded_download_dir = binascii.hexlify(download_dir.encode()).decode()
1✔
650
        return await self.db.execute_fetchall("update file set download_directory=?, file_name=? where stream_hash=?", (
1✔
651
            encoded_download_dir, encoded_file_name, stream_hash,
652
        ))
653

654
    async def save_content_fee(self, stream_hash: str, content_fee: Transaction):
3✔
655
        return await self.db.execute_fetchall("update file set content_fee=? where stream_hash=?", (
×
656
            binascii.hexlify(content_fee.raw), stream_hash,
657
        ))
658

659
    async def set_saved_file(self, stream_hash: str):
3✔
660
        return await self.db.execute_fetchall("update file set saved_file=1 where stream_hash=?", (
1✔
661
            stream_hash,
662
        ))
663

664
    async def clear_saved_file(self, stream_hash: str):
3✔
665
        return await self.db.execute_fetchall("update file set saved_file=0 where stream_hash=?", (
1✔
666
            stream_hash,
667
        ))
668

669
    async def recover_streams(self, descriptors_and_sds: typing.List[typing.Tuple['StreamDescriptor', 'BlobFile',
3✔
670
                                                                                  typing.Optional[Transaction]]],
671
                              download_directory: str):
672
        def _recover(transaction: sqlite3.Connection):
1✔
673
            stream_hashes = [x[0].stream_hash for x in descriptors_and_sds]
1✔
674
            for descriptor, sd_blob, content_fee in descriptors_and_sds:
1✔
675
                content_claim = transaction.execute(
1✔
676
                    "select * from content_claim where stream_hash=?", (descriptor.stream_hash, )
677
                ).fetchone()
678
                delete_stream(transaction, descriptor)  # this will also delete the content claim
1✔
679
                store_stream(transaction, sd_blob, descriptor)
1✔
680
                store_file(transaction, descriptor.stream_hash, os.path.basename(descriptor.suggested_file_name),
1✔
681
                           download_directory, 0.0, 'stopped', content_fee=content_fee)
682
                if content_claim:
1!
683
                    transaction.execute("insert or ignore into content_claim values (?, ?, ?)", content_claim)
1✔
684
            transaction.executemany(
1✔
685
                "update file set status='stopped' where stream_hash=?",
686
                ((stream_hash, ) for stream_hash in stream_hashes)
687
            ).fetchall()
688
            download_dir = binascii.hexlify(self.conf.download_dir.encode()).decode()
1✔
689
            transaction.executemany(
1✔
690
                "update file set download_directory=? where stream_hash=?",
691
                ((download_dir, stream_hash) for stream_hash in stream_hashes)
692
            ).fetchall()
693
        await self.db.run_with_foreign_keys_disabled(_recover)
1✔
694

695
    def get_all_stream_hashes(self):
3✔
696
        return self.run_and_return_list("select stream_hash from stream")
1✔
697

698
    # # # # # # # # # support functions # # # # # # # # #
699

700
    def save_supports(self, claim_id_to_supports: dict):
3✔
701
        # TODO: add 'address' to support items returned for a claim from lbrycrdd and lbryum-server
702
        def _save_support(transaction):
1✔
703
            bind = "({})".format(','.join(['?'] * len(claim_id_to_supports)))
1✔
704
            transaction.execute(
1✔
705
                f"delete from support where claim_id in {bind}", tuple(claim_id_to_supports.keys())
706
            ).fetchall()
707
            for claim_id, supports in claim_id_to_supports.items():
1✔
708
                for support in supports:
1✔
709
                    transaction.execute(
1✔
710
                        "insert into support values (?, ?, ?, ?)",
711
                        ("%s:%i" % (support['txid'], support['nout']), claim_id, lbc_to_dewies(support['amount']),
712
                         support.get('address', ""))
713
                    ).fetchall()
714
        return self.db.run(_save_support)
1✔
715

716
    def get_supports(self, *claim_ids):
3✔
717
        def _format_support(outpoint, supported_id, amount, address):
1✔
718
            return {
1✔
719
                "txid": outpoint.split(":")[0],
720
                "nout": int(outpoint.split(":")[1]),
721
                "claim_id": supported_id,
722
                "amount": dewies_to_lbc(amount),
723
                "address": address,
724
            }
725

726
        def _get_supports(transaction):
1✔
727
            return [
1✔
728
                _format_support(*support_info)
729
                for support_info in _batched_select(
730
                    transaction,
731
                    "select * from support where claim_id in {}",
732
                    claim_ids
733
                )
734
            ]
735

736
        return self.db.run(_get_supports)
1✔
737

738
    # # # # # # # # # claim functions # # # # # # # # #
739

740
    async def save_claims(self, claim_infos):
3✔
741
        claim_id_to_supports = {}
1✔
742
        update_file_callbacks = []
1✔
743

744
        def _save_claims(transaction):
1✔
745
            content_claims_to_update = []
1✔
746
            for claim_info in claim_infos:
1✔
747
                outpoint = "%s:%i" % (claim_info['txid'], claim_info['nout'])
1✔
748
                claim_id = claim_info['claim_id']
1✔
749
                name = claim_info['name']
1✔
750
                amount = lbc_to_dewies(claim_info['amount'])
1✔
751
                height = claim_info['height']
1✔
752
                address = claim_info['address']
1✔
753
                sequence = claim_info['claim_sequence']
1✔
754
                certificate_id = claim_info['value'].signing_channel_id
1✔
755
                try:
1✔
756
                    source_hash = claim_info['value'].stream.source.sd_hash
1✔
757
                except (AttributeError, ValueError):
×
758
                    source_hash = None
×
759
                serialized = binascii.hexlify(claim_info['value'].to_bytes())
1✔
760
                transaction.execute(
1✔
761
                    "insert or replace into claim values (?, ?, ?, ?, ?, ?, ?, ?, ?)",
762
                    (outpoint, claim_id, name, amount, height, serialized, certificate_id, address, sequence)
763
                ).fetchall()
764
                # if this response doesn't have support info don't overwrite the existing
765
                # support info
766
                if 'supports' in claim_info:
1!
767
                    claim_id_to_supports[claim_id] = claim_info['supports']
×
768
                if not source_hash:
1!
769
                    continue
×
770
                stream_hash = transaction.execute(
1✔
771
                    "select file.stream_hash from stream "
772
                    "inner join file on file.stream_hash=stream.stream_hash where sd_hash=?", (source_hash,)
773
                ).fetchone()
774
                if not stream_hash:
1!
775
                    continue
1✔
776
                stream_hash = stream_hash[0]
×
777
                known_outpoint = transaction.execute(
×
778
                    "select claim_outpoint from content_claim where stream_hash=?", (stream_hash,)
779
                ).fetchone()
780
                known_claim_id = transaction.execute(
×
781
                    "select claim_id from claim "
782
                    "inner join content_claim c3 ON claim.claim_outpoint=c3.claim_outpoint "
783
                    "where c3.stream_hash=?", (stream_hash,)
784
                ).fetchone()
785
                if not known_claim_id:
×
786
                    content_claims_to_update.append((stream_hash, outpoint))
×
787
                elif known_outpoint != outpoint:
×
788
                    content_claims_to_update.append((stream_hash, outpoint))
×
789
            for stream_hash, outpoint in content_claims_to_update:
1!
790
                self._save_content_claim(transaction, outpoint, stream_hash)
×
791
                if stream_hash in self.content_claim_callbacks:
×
792
                    update_file_callbacks.append(self.content_claim_callbacks[stream_hash]())
×
793

794
        await self.db.run(_save_claims)
1✔
795
        if update_file_callbacks:
1!
NEW
796
            await asyncio.wait(map(asyncio.create_task, update_file_callbacks))
×
797
        if claim_id_to_supports:
1!
798
            await self.save_supports(claim_id_to_supports)
×
799

800
    def save_claim_from_output(self, ledger, *outputs: Output):
3✔
801
        return self.save_claims([{
1✔
802
            "claim_id": output.claim_id,
803
            "name": output.claim_name,
804
            "amount": dewies_to_lbc(output.amount),
805
            "address": output.get_address(ledger),
806
            "txid": output.tx_ref.id,
807
            "nout": output.position,
808
            "value": output.claim,
809
            "height": output.tx_ref.height,
810
            "claim_sequence": -1,
811
        } for output in outputs])
812

813
    def save_claims_for_resolve(self, claim_infos):
3✔
814
        to_save = {}
×
815
        for info in claim_infos:
×
816
            if 'value' in info:
×
817
                if info['value']:
×
818
                    to_save[info['claim_id']] = info
×
819
            else:
820
                for key in ('certificate', 'claim'):
×
821
                    if info.get(key, {}).get('value'):
×
822
                        to_save[info[key]['claim_id']] = info[key]
×
823
        return self.save_claims(to_save.values())
×
824

825
    @staticmethod
3✔
826
    def _save_content_claim(transaction, claim_outpoint, stream_hash=None, bt_infohash=None):
3✔
827
        assert stream_hash or bt_infohash
1✔
828
        # get the claim id and serialized metadata
829
        claim_info = transaction.execute(
1✔
830
            "select claim_id, serialized_metadata from claim where claim_outpoint=?", (claim_outpoint,)
831
        ).fetchone()
832
        if not claim_info:
1!
833
            raise Exception("claim not found")
×
834
        new_claim_id, claim = claim_info[0], Claim.from_bytes(binascii.unhexlify(claim_info[1]))
1✔
835

836
        # certificate claims should not be in the content_claim table
837
        if not claim.is_stream:
1!
838
            raise Exception("claim does not contain a stream")
×
839

840
        # get the known sd hash for this stream
841
        known_sd_hash = transaction.execute(
1✔
842
            "select sd_hash from stream where stream_hash=?", (stream_hash,)
843
        ).fetchone()
844
        if not known_sd_hash:
1!
845
            raise Exception("stream not found")
×
846
        # check the claim contains the same sd hash
847
        if known_sd_hash[0] != claim.stream.source.sd_hash:
1!
848
            raise Exception("stream mismatch")
×
849

850
        # if there is a current claim associated to the file, check that the new claim is an update to it
851
        current_associated_content = transaction.execute(
1✔
852
            "select claim_outpoint from content_claim where stream_hash=?", (stream_hash,)
853
        ).fetchone()
854
        if current_associated_content:
1!
855
            current_associated_claim_id = transaction.execute(
×
856
                "select claim_id from claim where claim_outpoint=?", current_associated_content
857
            ).fetchone()[0]
858
            if current_associated_claim_id != new_claim_id:
×
859
                raise Exception(
×
860
                    f"mismatching claim ids when updating stream {current_associated_claim_id} vs {new_claim_id}"
861
                )
862

863
        # update the claim associated to the file
864
        transaction.execute("delete from content_claim where stream_hash=?", (stream_hash, )).fetchall()
1✔
865
        transaction.execute(
1✔
866
            "insert into content_claim values (?, NULL, ?)", (stream_hash, claim_outpoint)
867
        ).fetchall()
868

869
    async def save_content_claim(self, stream_hash, claim_outpoint):
3✔
870
        await self.db.run(self._save_content_claim, claim_outpoint, stream_hash)
1✔
871
        # update corresponding ManagedEncryptedFileDownloader object
872
        if stream_hash in self.content_claim_callbacks:
1!
873
            await self.content_claim_callbacks[stream_hash]()
1✔
874

875
    async def save_torrent_content_claim(self, bt_infohash, claim_outpoint, length, name):
3✔
876
        def _save_torrent(transaction):
×
877
            transaction.execute(
×
878
                "insert or replace into torrent values (?, NULL, ?, ?)", (bt_infohash, length, name)
879
            ).fetchall()
880
            transaction.execute(
×
881
                "insert or replace into content_claim values (NULL, ?, ?)", (bt_infohash, claim_outpoint)
882
            ).fetchall()
883
        await self.db.run(_save_torrent)
×
884
        # update corresponding ManagedEncryptedFileDownloader object
885
        if bt_infohash in self.content_claim_callbacks:
×
886
            await self.content_claim_callbacks[bt_infohash]()
×
887

888
    async def get_content_claim(self, stream_hash: str, include_supports: typing.Optional[bool] = True) -> typing.Dict:
3✔
889
        claims = await self.db.run(get_claims_from_stream_hashes, [stream_hash])
1✔
890
        claim = None
1✔
891
        if claims:
1!
892
            claim = claims[stream_hash].as_dict()
1✔
893
            if include_supports:
1!
894
                supports = await self.get_supports(claim['claim_id'])
1✔
895
                claim['supports'] = supports
1✔
896
                claim['effective_amount'] = calculate_effective_amount(claim['amount'], supports)
1✔
897
        return claim
1✔
898

899
    async def get_content_claim_for_torrent(self, bt_infohash):
3✔
900
        claims = await self.db.run(get_claims_from_torrent_info_hashes, [bt_infohash])
×
901
        return claims[bt_infohash].as_dict() if claims else None
×
902

903
    # # # # # # # # # reflector functions # # # # # # # # #
904

905
    def update_reflected_stream(self, sd_hash, reflector_address, success=True):
3✔
906
        if success:
1!
907
            return self.db.execute_fetchall(
1✔
908
                "insert or replace into reflected_stream values (?, ?, ?)",
909
                (sd_hash, reflector_address, self.time_getter())
910
            )
911
        return self.db.execute_fetchall(
×
912
            "delete from reflected_stream where sd_hash=? and reflector_address=?",
913
            (sd_hash, reflector_address)
914
        )
915

916
    def get_streams_to_re_reflect(self):
3✔
917
        return self.run_and_return_list(
1✔
918
            "select s.sd_hash from stream s "
919
            "left outer join reflected_stream r on s.sd_hash=r.sd_hash "
920
            "where r.timestamp is null or r.timestamp < ?",
921
            int(self.time_getter()) - 86400
922
        )
923

924
    # # # # # # # # # # dht functions # # # # # # # # # # #
925
    async def get_persisted_kademlia_peers(self) -> typing.List[typing.Tuple[bytes, str, int, int]]:
3✔
926
        query = 'select node_id, address, udp_port, tcp_port from peer'
1✔
927
        return [(binascii.unhexlify(n), a, u, t) for n, a, u, t in await self.db.execute_fetchall(query)]
1✔
928

929
    async def save_kademlia_peers(self, peers: typing.List['KademliaPeer']):
3✔
930
        def _save_kademlia_peers(transaction: sqlite3.Connection):
1✔
931
            transaction.execute('delete from peer').fetchall()
1✔
932
            transaction.executemany(
1✔
933
                'insert into peer(node_id, address, udp_port, tcp_port) values (?, ?, ?, ?)',
934
                ((binascii.hexlify(p.node_id), p.address, p.udp_port, p.tcp_port) for p in peers)
935
            ).fetchall()
936
        return await self.db.run(_save_kademlia_peers)
1✔
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc