]> git.rkrishnan.org Git - tahoe-lafs/tahoe-lafs.git/blob - src/allmydata/interfaces.py
Default arguments in interface declarations should only be used to specify a default...
[tahoe-lafs/tahoe-lafs.git] / src / allmydata / interfaces.py
1
2 from zope.interface import Interface
3 from foolscap.api import StringConstraint, ListOf, TupleOf, SetOf, DictOf, \
4      ChoiceOf, IntegerConstraint, Any, RemoteInterface, Referenceable
5
6 HASH_SIZE=32
7 SALT_SIZE=16
8
9 SDMF_VERSION=0
10 MDMF_VERSION=1
11
12 Hash = StringConstraint(maxLength=HASH_SIZE,
13                         minLength=HASH_SIZE)# binary format 32-byte SHA256 hash
14 Nodeid = StringConstraint(maxLength=20,
15                           minLength=20) # binary format 20-byte SHA1 hash
16 FURL = StringConstraint(1000)
17 StorageIndex = StringConstraint(16)
18 URI = StringConstraint(300) # kind of arbitrary
19
20 MAX_BUCKETS = 256  # per peer -- zfec offers at most 256 shares per file
21
22 DEFAULT_MAX_SEGMENT_SIZE = 128*1024
23
24 ShareData = StringConstraint(None)
25 URIExtensionData = StringConstraint(1000)
26 Number = IntegerConstraint(8) # 2**(8*8) == 16EiB ~= 18e18 ~= 18 exabytes
27 Offset = Number
28 ReadSize = int # the 'int' constraint is 2**31 == 2Gib -- large files are processed in not-so-large increments
29 WriteEnablerSecret = Hash # used to protect mutable bucket modifications
30 LeaseRenewSecret = Hash # used to protect bucket lease renewal requests
31 LeaseCancelSecret = Hash # used to protect bucket lease cancellation requests
32
33 class RIBucketWriter(RemoteInterface):
34     """ Objects of this kind live on the server side. """
35     def write(offset=Offset, data=ShareData):
36         return None
37
38     def close():
39         """
40         If the data that has been written is incomplete or inconsistent then
41         the server will throw the data away, else it will store it for future
42         retrieval.
43         """
44         return None
45
46     def abort():
47         """Abandon all the data that has been written.
48         """
49         return None
50
51
52 class RIBucketReader(RemoteInterface):
53     def read(offset=Offset, length=ReadSize):
54         return ShareData
55
56     def advise_corrupt_share(reason=str):
57         """Clients who discover hash failures in shares that they have
58         downloaded from me will use this method to inform me about the
59         failures. I will record their concern so that my operator can
60         manually inspect the shares in question. I return None.
61
62         This is a wrapper around RIStorageServer.advise_corrupt_share(),
63         which is tied to a specific share, and therefore does not need the
64         extra share-identifying arguments. Please see that method for full
65         documentation.
66         """
67
68
69 TestVector = ListOf(TupleOf(Offset, ReadSize, str, str))
70 # elements are (offset, length, operator, specimen)
71 # operator is one of "lt, le, eq, ne, ge, gt"
72 # nop always passes and is used to fetch data while writing.
73 # you should use length==len(specimen) for everything except nop
74 DataVector = ListOf(TupleOf(Offset, ShareData))
75 # (offset, data). This limits us to 30 writes of 1MiB each per call
76 TestAndWriteVectorsForShares = DictOf(int,
77                                       TupleOf(TestVector,
78                                               DataVector,
79                                               ChoiceOf(None, Offset), # new_length
80                                               ))
81 ReadVector = ListOf(TupleOf(Offset, ReadSize))
82 ReadData = ListOf(ShareData)
83 # returns data[offset:offset+length] for each element of TestVector
84
85
86 class RIStorageServer(RemoteInterface):
87     __remote_name__ = "RIStorageServer.tahoe.allmydata.com"
88
89     def get_version():
90         """
91         Return a dictionary of version information.
92         """
93         return DictOf(str, Any())
94
95     def allocate_buckets(storage_index=StorageIndex,
96                          renew_secret=LeaseRenewSecret,
97                          cancel_secret=LeaseCancelSecret,
98                          sharenums=SetOf(int, maxLength=MAX_BUCKETS),
99                          allocated_size=Offset, canary=Referenceable):
100         """
101         @param storage_index: the index of the bucket to be created or
102                               increfed.
103         @param sharenums: these are the share numbers (probably between 0 and
104                           99) that the sender is proposing to store on this
105                           server.
106         @param renew_secret: This is the secret used to protect bucket refresh
107                              This secret is generated by the client and
108                              stored for later comparison by the server. Each
109                              server is given a different secret.
110         @param cancel_secret: Like renew_secret, but protects bucket decref.
111         @param canary: If the canary is lost before close(), the bucket is
112                        deleted.
113         @return: tuple of (alreadygot, allocated), where alreadygot is what we
114                  already have and allocated is what we hereby agree to accept.
115                  New leases are added for shares in both lists.
116         """
117         return TupleOf(SetOf(int, maxLength=MAX_BUCKETS),
118                        DictOf(int, RIBucketWriter, maxKeys=MAX_BUCKETS))
119
120     def add_lease(storage_index=StorageIndex,
121                   renew_secret=LeaseRenewSecret,
122                   cancel_secret=LeaseCancelSecret):
123         """
124         Add a new lease on the given bucket. If the renew_secret matches an
125         existing lease, that lease will be renewed instead. If there is no
126         bucket for the given storage_index, return silently. (note that in
127         tahoe-1.3.0 and earlier, IndexError was raised if there was no
128         bucket)
129         """
130         return Any() # returns None now, but future versions might change
131
132     def renew_lease(storage_index=StorageIndex, renew_secret=LeaseRenewSecret):
133         """
134         Renew the lease on a given bucket, resetting the timer to 31 days.
135         Some networks will use this, some will not. If there is no bucket for
136         the given storage_index, IndexError will be raised.
137
138         For mutable shares, if the given renew_secret does not match an
139         existing lease, IndexError will be raised with a note listing the
140         server-nodeids on the existing leases, so leases on migrated shares
141         can be renewed or cancelled. For immutable shares, IndexError
142         (without the note) will be raised.
143         """
144         return Any()
145
146     def get_buckets(storage_index=StorageIndex):
147         return DictOf(int, RIBucketReader, maxKeys=MAX_BUCKETS)
148
149
150
151     def slot_readv(storage_index=StorageIndex,
152                    shares=ListOf(int), readv=ReadVector):
153         """Read a vector from the numbered shares associated with the given
154         storage index. An empty shares list means to return data from all
155         known shares. Returns a dictionary with one key per share."""
156         return DictOf(int, ReadData) # shnum -> results
157
158     def slot_testv_and_readv_and_writev(storage_index=StorageIndex,
159                                         secrets=TupleOf(WriteEnablerSecret,
160                                                         LeaseRenewSecret,
161                                                         LeaseCancelSecret),
162                                         tw_vectors=TestAndWriteVectorsForShares,
163                                         r_vector=ReadVector,
164                                         ):
165         """
166         General-purpose test-read-and-set operation for mutable slots:
167         (1) For submitted shnums, compare the test vectors against extant
168             shares, or against an empty share for shnums that do not exist.
169         (2) Use the read vectors to extract "old data" from extant shares.
170         (3) If all tests in (1) passed, then apply the write vectors
171             (possibly creating new shares).
172         (4) Return whether the tests passed, and the "old data", which does
173             not include any modifications made by the writes.
174
175         The operation does not interleave with other operations on the same
176         shareset.
177
178         This method is, um, large. The goal is to allow clients to update all
179         the shares associated with a mutable file in a single round trip.
180
181         @param storage_index: the index of the bucket to be created or
182                               increfed.
183         @param write_enabler: a secret that is stored along with the slot.
184                               Writes are accepted from any caller who can
185                               present the matching secret. A different secret
186                               should be used for each slot*server pair.
187         @param renew_secret: This is the secret used to protect bucket refresh
188                              This secret is generated by the client and
189                              stored for later comparison by the server. Each
190                              server is given a different secret.
191         @param cancel_secret: Like renew_secret, but protects bucket decref.
192
193         The 'secrets' argument is a tuple of (write_enabler, renew_secret,
194         cancel_secret). The first is required to perform any write. The
195         latter two are used when allocating new shares. To simply acquire a
196         new lease on existing shares, use an empty testv and an empty writev.
197
198         Each share can have a separate test vector (i.e. a list of
199         comparisons to perform). If all vectors for all shares pass, then all
200         writes for all shares are recorded. Each comparison is a 4-tuple of
201         (offset, length, operator, specimen), which effectively does a
202         bool( (read(offset, length)) OPERATOR specimen ) and only performs
203         the write if all these evaluate to True. Basic test-and-set uses 'eq'.
204         Write-if-newer uses a seqnum and (offset, length, 'lt', specimen).
205         Write-if-same-or-newer uses 'le'.
206
207         Reads from the end of the container are truncated, and missing shares
208         behave like empty ones, so to assert that a share doesn't exist (for
209         use when creating a new share), use (0, 1, 'eq', '').
210
211         The write vector will be applied to the given share, expanding it if
212         necessary. A write vector applied to a share number that did not
213         exist previously will cause that share to be created. Write vectors
214         must not overlap (if they do, this will either cause an error or
215         apply them in an unspecified order). Duplicate write vectors, with
216         the same offset and data, are currently tolerated but are not
217         desirable.
218
219         In Tahoe-LAFS v1.8.3 or later (except 1.9.0a1), if you send a write
220         vector whose offset is beyond the end of the current data, the space
221         between the end of the current data and the beginning of the write
222         vector will be filled with zero bytes. In earlier versions the
223         contents of this space was unspecified (and might end up containing
224         secrets). Storage servers with the new zero-filling behavior will
225         advertise a true value for the 'fills-holes-with-zero-bytes' key
226         (under 'http://allmydata.org/tahoe/protocols/storage/v1') in their
227         version information.
228
229         Each write vector is accompanied by a 'new_length' argument, which
230         can be used to truncate the data. If new_length is not None and it is
231         less than the current size of the data (after applying all write
232         vectors), then the data will be truncated to new_length. If
233         new_length==0, the share will be deleted.
234
235         In Tahoe-LAFS v1.8.2 and earlier, new_length could also be used to
236         enlarge the file by sending a number larger than the size of the data
237         after applying all write vectors. That behavior was not used, and as
238         of Tahoe-LAFS v1.8.3 it no longer works and the new_length is ignored
239         in that case.
240
241         If a storage client knows that the server supports zero-filling, for
242         example from the 'fills-holes-with-zero-bytes' key in its version
243         information, it can extend the file efficiently by writing a single
244         zero byte just before the new end-of-file. Otherwise it must
245         explicitly write zeroes to all bytes between the old and new
246         end-of-file. In any case it should avoid sending new_length larger
247         than the size of the data after applying all write vectors.
248
249         The read vector is used to extract data from all known shares,
250         *before* any writes have been applied. The same read vector is used
251         for all shares. This captures the state that was tested by the test
252         vector, for extant shares.
253
254         This method returns two values: a boolean and a dict. The boolean is
255         True if the write vectors were applied, False if not. The dict is
256         keyed by share number, and each value contains a list of strings, one
257         for each element of the read vector.
258
259         If the write_enabler is wrong, this will raise BadWriteEnablerError.
260         To enable share migration (using update_write_enabler), the exception
261         will have the nodeid used for the old write enabler embedded in it,
262         in the following string::
263
264          The write enabler was recorded by nodeid '%s'.
265
266         Note that the nodeid here is encoded using the same base32 encoding
267         used by Foolscap and allmydata.util.idlib.nodeid_b2a().
268         """
269         return TupleOf(bool, DictOf(int, ReadData))
270
271     def advise_corrupt_share(share_type=str, storage_index=StorageIndex,
272                              shnum=int, reason=str):
273         """Clients who discover hash failures in shares that they have
274         downloaded from me will use this method to inform me about the
275         failures. I will record their concern so that my operator can
276         manually inspect the shares in question. I return None.
277
278         'share_type' is either 'mutable' or 'immutable'. 'storage_index' is a
279         (binary) storage index string, and 'shnum' is the integer share
280         number. 'reason' is a human-readable explanation of the problem,
281         probably including some expected hash values and the computed ones
282         which did not match. Corruption advisories for mutable shares should
283         include a hash of the public key (the same value that appears in the
284         mutable-file verify-cap), since the current share format does not
285         store that on disk.
286         """
287
288
289 class IStorageBucketWriter(Interface):
290     """
291     Objects of this kind live on the client side.
292     """
293     def put_block(segmentnum, data):
294         """
295         @param segmentnum=int
296         @param data=ShareData: For most segments, this data will be 'blocksize'
297         bytes in length. The last segment might be shorter.
298         @return: a Deferred that fires (with None) when the operation completes
299         """
300
301     def put_crypttext_hashes(hashes):
302         """
303         @param hashes=ListOf(Hash)
304         @return: a Deferred that fires (with None) when the operation completes
305         """
306
307     def put_block_hashes(blockhashes):
308         """
309         @param blockhashes=ListOf(Hash)
310         @return: a Deferred that fires (with None) when the operation completes
311         """
312
313     def put_share_hashes(sharehashes):
314         """
315         @param sharehashes=ListOf(TupleOf(int, Hash))
316         @return: a Deferred that fires (with None) when the operation completes
317         """
318
319     def put_uri_extension(data):
320         """This block of data contains integrity-checking information (hashes
321         of plaintext, crypttext, and shares), as well as encoding parameters
322         that are necessary to recover the data. This is a serialized dict
323         mapping strings to other strings. The hash of this data is kept in
324         the URI and verified before any of the data is used. All buckets for
325         a given file contain identical copies of this data.
326
327         The serialization format is specified with the following pseudocode:
328         for k in sorted(dict.keys()):
329             assert re.match(r'^[a-zA-Z_\-]+$', k)
330             write(k + ':' + netstring(dict[k]))
331
332         @param data=URIExtensionData
333         @return: a Deferred that fires (with None) when the operation completes
334         """
335
336     def close():
337         """Finish writing and close the bucket. The share is not finalized
338         until this method is called: if the uploading client disconnects
339         before calling close(), the partially-written share will be
340         discarded.
341
342         @return: a Deferred that fires (with None) when the operation completes
343         """
344
345
346 class IStorageBucketReader(Interface):
347     def get_block_data(blocknum, blocksize, size):
348         """Most blocks will be the same size. The last block might be shorter
349         than the others.
350
351         @param blocknum=int
352         @param blocksize=int
353         @param size=int
354         @return: ShareData
355         """
356
357     def get_crypttext_hashes():
358         """
359         @return: ListOf(Hash)
360         """
361
362     def get_block_hashes(at_least_these=()):
363         """
364         @param at_least_these=SetOf(int)
365         @return: ListOf(Hash)
366         """
367
368     def get_share_hashes():
369         """
370         @return: ListOf(TupleOf(int, Hash))
371         """
372
373     def get_uri_extension():
374         """
375         @return: URIExtensionData
376         """
377
378
379 class IStorageBroker(Interface):
380     def get_servers_for_psi(peer_selection_index):
381         """
382         @return: list of IServer instances
383         """
384     def get_connected_servers():
385         """
386         @return: frozenset of connected IServer instances
387         """
388     def get_known_servers():
389         """
390         @return: frozenset of IServer instances
391         """
392     def get_all_serverids():
393         """
394         @return: frozenset of serverid strings
395         """
396     def get_nickname_for_serverid(serverid):
397         """
398         @return: unicode nickname, or None
399         """
400
401     # methods moved from IntroducerClient, need review
402     def get_all_connections():
403         """Return a frozenset of (nodeid, service_name, rref) tuples, one for
404         each active connection we've established to a remote service. This is
405         mostly useful for unit tests that need to wait until a certain number
406         of connections have been made."""
407
408     def get_all_connectors():
409         """Return a dict that maps from (nodeid, service_name) to a
410         RemoteServiceConnector instance for all services that we are actively
411         trying to connect to. Each RemoteServiceConnector has the following
412         public attributes::
413
414           service_name: the type of service provided, like 'storage'
415           announcement_time: when we first heard about this service
416           last_connect_time: when we last established a connection
417           last_loss_time: when we last lost a connection
418
419           version: the peer's version, from the most recent connection
420           oldest_supported: the peer's oldest supported version, same
421
422           rref: the RemoteReference, if connected, otherwise None
423           remote_host: the IAddress, if connected, otherwise None
424
425         This method is intended for monitoring interfaces, such as a web page
426         which describes connecting and connected peers.
427         """
428
429     def get_all_peerids():
430         """Return a frozenset of all peerids to whom we have a connection (to
431         one or more services) established. Mostly useful for unit tests."""
432
433     def get_all_connections_for(service_name):
434         """Return a frozenset of (nodeid, service_name, rref) tuples, one
435         for each active connection that provides the given SERVICE_NAME."""
436
437     def get_permuted_peers(service_name, key):
438         """Returns an ordered list of (peerid, rref) tuples, selecting from
439         the connections that provide SERVICE_NAME, using a hash-based
440         permutation keyed by KEY. This randomizes the service list in a
441         repeatable way, to distribute load over many peers.
442         """
443
444
445 class IDisplayableServer(Interface):
446     def get_nickname():
447         pass
448
449     def get_name():
450         pass
451
452     def get_longname():
453         pass
454
455
456 class IServer(IDisplayableServer):
457     """I live in the client, and represent a single server."""
458     def start_connecting(tub, trigger_cb):
459         pass
460
461     def get_rref():
462         """Once a server is connected, I return a RemoteReference.
463         Before a server is connected for the first time, I return None.
464
465         Note that the rref I return will start producing DeadReferenceErrors
466         once the connection is lost.
467         """
468
469
470 class IMutableSlotWriter(Interface):
471     """
472     The interface for a writer around a mutable slot on a remote server.
473     """
474     def set_checkstring(checkstring, *args):
475         """
476         Set the checkstring that I will pass to the remote server when
477         writing.
478
479             @param checkstring A packed checkstring to use.
480
481         Note that implementations can differ in which semantics they
482         wish to support for set_checkstring -- they can, for example,
483         build the checkstring themselves from its constituents, or
484         some other thing.
485         """
486
487     def get_checkstring():
488         """
489         Get the checkstring that I think currently exists on the remote
490         server.
491         """
492
493     def put_block(data, segnum, salt):
494         """
495         Add a block and salt to the share.
496         """
497
498     def put_encprivkey(encprivkey):
499         """
500         Add the encrypted private key to the share.
501         """
502
503     def put_blockhashes(blockhashes):
504         """
505         @param blockhashes=list
506         Add the block hash tree to the share.
507         """
508
509     def put_sharehashes(sharehashes):
510         """
511         @param sharehashes=dict
512         Add the share hash chain to the share.
513         """
514
515     def get_signable():
516         """
517         Return the part of the share that needs to be signed.
518         """
519
520     def put_signature(signature):
521         """
522         Add the signature to the share.
523         """
524
525     def put_verification_key(verification_key):
526         """
527         Add the verification key to the share.
528         """
529
530     def finish_publishing():
531         """
532         Do anything necessary to finish writing the share to a remote
533         server. I require that no further publishing needs to take place
534         after this method has been called.
535         """
536
537
538 class IURI(Interface):
539     def init_from_string(uri):
540         """Accept a string (as created by my to_string() method) and populate
541         this instance with its data. I am not normally called directly,
542         please use the module-level uri.from_string() function to convert
543         arbitrary URI strings into IURI-providing instances."""
544
545     def is_readonly():
546         """Return False if this URI be used to modify the data. Return True
547         if this URI cannot be used to modify the data."""
548
549     def is_mutable():
550         """Return True if the data can be modified by *somebody* (perhaps
551         someone who has a more powerful URI than this one)."""
552
553     # TODO: rename to get_read_cap()
554     def get_readonly():
555         """Return another IURI instance, which represents a read-only form of
556         this one. If is_readonly() is True, this returns self."""
557
558     def get_verify_cap():
559         """Return an instance that provides IVerifierURI, which can be used
560         to check on the availability of the file or directory, without
561         providing enough capabilities to actually read or modify the
562         contents. This may return None if the file does not need checking or
563         verification (e.g. LIT URIs).
564         """
565
566     def to_string():
567         """Return a string of printable ASCII characters, suitable for
568         passing into init_from_string."""
569
570
571 class IVerifierURI(Interface, IURI):
572     def init_from_string(uri):
573         """Accept a string (as created by my to_string() method) and populate
574         this instance with its data. I am not normally called directly,
575         please use the module-level uri.from_string() function to convert
576         arbitrary URI strings into IURI-providing instances."""
577
578     def to_string():
579         """Return a string of printable ASCII characters, suitable for
580         passing into init_from_string."""
581
582
583 class IDirnodeURI(Interface):
584     """I am a URI which represents a dirnode."""
585
586 class IFileURI(Interface):
587     """I am a URI which represents a filenode."""
588     def get_size():
589         """Return the length (in bytes) of the file that I represent."""
590
591
592 class IImmutableFileURI(IFileURI):
593     pass
594
595 class IMutableFileURI(Interface):
596     pass
597
598 class IDirectoryURI(Interface):
599     pass
600
601 class IReadonlyDirectoryURI(Interface):
602     pass
603
604
605 class CapConstraintError(Exception):
606     """A constraint on a cap was violated."""
607
608 class MustBeDeepImmutableError(CapConstraintError):
609     """Mutable children cannot be added to an immutable directory.
610     Also, caps obtained from an immutable directory can trigger this error
611     if they are later found to refer to a mutable object and then used."""
612
613 class MustBeReadonlyError(CapConstraintError):
614     """Known write caps cannot be specified in a ro_uri field. Also,
615     caps obtained from a ro_uri field can trigger this error if they
616     are later found to be write caps and then used."""
617
618 class MustNotBeUnknownRWError(CapConstraintError):
619     """Cannot add an unknown child cap specified in a rw_uri field."""
620
621
622 class IReadable(Interface):
623     """I represent a readable object -- either an immutable file, or a
624     specific version of a mutable file.
625     """
626
627     def is_readonly():
628         """Return True if this reference provides mutable access to the given
629         file or directory (i.e. if you can modify it), or False if not. Note
630         that even if this reference is read-only, someone else may hold a
631         read-write reference to it.
632
633         For an IReadable returned by get_best_readable_version(), this will
634         always return True, but for instances of subinterfaces such as
635         IMutableFileVersion, it may return False."""
636
637     def is_mutable():
638         """Return True if this file or directory is mutable (by *somebody*,
639         not necessarily you), False if it is is immutable. Note that a file
640         might be mutable overall, but your reference to it might be
641         read-only. On the other hand, all references to an immutable file
642         will be read-only; there are no read-write references to an immutable
643         file."""
644
645     def get_storage_index():
646         """Return the storage index of the file."""
647
648     def get_size():
649         """Return the length (in bytes) of this readable object."""
650
651     def download_to_data():
652         """Download all of the file contents. I return a Deferred that fires
653         with the contents as a byte string."""
654
655     def read(consumer, offset=0, size=None):
656         """Download a portion (possibly all) of the file's contents, making
657         them available to the given IConsumer. Return a Deferred that fires
658         (with the consumer) when the consumer is unregistered (either because
659         the last byte has been given to it, or because the consumer threw an
660         exception during write(), possibly because it no longer wants to
661         receive data). The portion downloaded will start at 'offset' and
662         contain 'size' bytes (or the remainder of the file if size==None).
663
664         The consumer will be used in non-streaming mode: an IPullProducer
665         will be attached to it.
666
667         The consumer will not receive data right away: several network trips
668         must occur first. The order of events will be::
669
670          consumer.registerProducer(p, streaming)
671           (if streaming == False)::
672            consumer does p.resumeProducing()
673             consumer.write(data)
674            consumer does p.resumeProducing()
675             consumer.write(data).. (repeat until all data is written)
676          consumer.unregisterProducer()
677          deferred.callback(consumer)
678
679         If a download error occurs, or an exception is raised by
680         consumer.registerProducer() or consumer.write(), I will call
681         consumer.unregisterProducer() and then deliver the exception via
682         deferred.errback(). To cancel the download, the consumer should call
683         p.stopProducing(), which will result in an exception being delivered
684         via deferred.errback().
685
686         See src/allmydata/util/consumer.py for an example of a simple
687         download-to-memory consumer.
688         """
689
690
691 class IWriteable(Interface):
692     """
693     I define methods that callers can use to update SDMF and MDMF
694     mutable files on a Tahoe-LAFS grid.
695     """
696     # XXX: For the moment, we have only this. It is possible that we
697     #      want to move overwrite() and modify() in here too.
698     def update(data, offset):
699         """
700         I write the data from my data argument to the MDMF file,
701         starting at offset. I continue writing data until my data
702         argument is exhausted, appending data to the file as necessary.
703         """
704         # assert IMutableUploadable.providedBy(data)
705         # to append data: offset=node.get_size_of_best_version()
706         # do we want to support compacting MDMF?
707         # for an MDMF file, this can be done with O(data.get_size())
708         # memory. For an SDMF file, any modification takes
709         # O(node.get_size_of_best_version()).
710
711
712 class IMutableFileVersion(IReadable):
713     """I provide access to a particular version of a mutable file. The
714     access is read/write if I was obtained from a filenode derived from
715     a write cap, or read-only if the filenode was derived from a read cap.
716     """
717
718     def get_sequence_number():
719         """Return the sequence number of this version."""
720
721     def get_servermap():
722         """Return the IMutableFileServerMap instance that was used to create
723         this object.
724         """
725
726     def get_writekey():
727         """Return this filenode's writekey, or None if the node does not have
728         write-capability. This may be used to assist with data structures
729         that need to make certain data available only to writers, such as the
730         read-write child caps in dirnodes. The recommended process is to have
731         reader-visible data be submitted to the filenode in the clear (where
732         it will be encrypted by the filenode using the readkey), but encrypt
733         writer-visible data using this writekey.
734         """
735
736     # TODO: Can this be overwrite instead of replace?
737     def replace(new_contents):
738         """Replace the contents of the mutable file, provided that no other
739         node has published (or is attempting to publish, concurrently) a
740         newer version of the file than this one.
741
742         I will avoid modifying any share that is different than the version
743         given by get_sequence_number(). However, if another node is writing
744         to the file at the same time as me, I may manage to update some shares
745         while they update others. If I see any evidence of this, I will signal
746         UncoordinatedWriteError, and the file will be left in an inconsistent
747         state (possibly the version you provided, possibly the old version,
748         possibly somebody else's version, and possibly a mix of shares from
749         all of these).
750
751         The recommended response to UncoordinatedWriteError is to either
752         return it to the caller (since they failed to coordinate their
753         writes), or to attempt some sort of recovery. It may be sufficient to
754         wait a random interval (with exponential backoff) and repeat your
755         operation. If I do not signal UncoordinatedWriteError, then I was
756         able to write the new version without incident.
757
758         I return a Deferred that fires (with a PublishStatus object) when the
759         update has completed.
760         """
761
762     def modify(modifier_cb):
763         """Modify the contents of the file, by downloading this version,
764         applying the modifier function (or bound method), then uploading
765         the new version. This will succeed as long as no other node
766         publishes a version between the download and the upload.
767         I return a Deferred that fires (with a PublishStatus object) when
768         the update is complete.
769
770         The modifier callable will be given three arguments: a string (with
771         the old contents), a 'first_time' boolean, and a servermap. As with
772         download_to_data(), the old contents will be from this version,
773         but the modifier can use the servermap to make other decisions
774         (such as refusing to apply the delta if there are multiple parallel
775         versions, or if there is evidence of a newer unrecoverable version).
776         'first_time' will be True the first time the modifier is called,
777         and False on any subsequent calls.
778
779         The callable should return a string with the new contents. The
780         callable must be prepared to be called multiple times, and must
781         examine the input string to see if the change that it wants to make
782         is already present in the old version. If it does not need to make
783         any changes, it can either return None, or return its input string.
784
785         If the modifier raises an exception, it will be returned in the
786         errback.
787         """
788
789
790 # The hierarchy looks like this:
791 #  IFilesystemNode
792 #   IFileNode
793 #    IMutableFileNode
794 #    IImmutableFileNode
795 #   IDirectoryNode
796
797 class IFilesystemNode(Interface):
798     def get_cap():
799         """Return the strongest 'cap instance' associated with this node.
800         (writecap for writeable-mutable files/directories, readcap for
801         immutable or readonly-mutable files/directories). To convert this
802         into a string, call .to_string() on the result."""
803
804     def get_readcap():
805         """Return a readonly cap instance for this node. For immutable or
806         readonly nodes, get_cap() and get_readcap() return the same thing."""
807
808     def get_repair_cap():
809         """Return an IURI instance that can be used to repair the file, or
810         None if this node cannot be repaired (either because it is not
811         distributed, like a LIT file, or because the node does not represent
812         sufficient authority to create a repair-cap, like a read-only RSA
813         mutable file node [which cannot create the correct write-enablers]).
814         """
815
816     def get_verify_cap():
817         """Return an IVerifierURI instance that represents the
818         'verifiy/refresh capability' for this node. The holder of this
819         capability will be able to renew the lease for this node, protecting
820         it from garbage-collection. They will also be able to ask a server if
821         it holds a share for the file or directory.
822         """
823
824     def get_uri():
825         """Return the URI string corresponding to the strongest cap associated
826         with this node. If this node is read-only, the URI will only offer
827         read-only access. If this node is read-write, the URI will offer
828         read-write access.
829
830         If you have read-write access to a node and wish to share merely
831         read-only access with others, use get_readonly_uri().
832         """
833
834     def get_write_uri():
835         """Return the URI string that can be used by others to get write
836         access to this node, if it is writeable. If this is a read-only node,
837         return None."""
838
839     def get_readonly_uri():
840         """Return the URI string that can be used by others to get read-only
841         access to this node. The result is a read-only URI, regardless of
842         whether this node is read-only or read-write.
843
844         If you have merely read-only access to this node, get_readonly_uri()
845         will return the same thing as get_uri().
846         """
847
848     def get_storage_index():
849         """Return a string with the (binary) storage index in use on this
850         download. This may be None if there is no storage index (i.e. LIT
851         files and directories)."""
852
853     def is_readonly():
854         """Return True if this reference provides mutable access to the given
855         file or directory (i.e. if you can modify it), or False if not. Note
856         that even if this reference is read-only, someone else may hold a
857         read-write reference to it."""
858
859     def is_mutable():
860         """Return True if this file or directory is mutable (by *somebody*,
861         not necessarily you), False if it is is immutable. Note that a file
862         might be mutable overall, but your reference to it might be
863         read-only. On the other hand, all references to an immutable file
864         will be read-only; there are no read-write references to an immutable
865         file.
866         """
867
868     def is_unknown():
869         """Return True if this is an unknown node."""
870
871     def is_allowed_in_immutable_directory():
872         """Return True if this node is allowed as a child of a deep-immutable
873         directory. This is true if either the node is of a known-immutable type,
874         or it is unknown and read-only.
875         """
876
877     def raise_error():
878         """Raise any error associated with this node."""
879
880     # XXX: These may not be appropriate outside the context of an IReadable.
881     def get_size():
882         """Return the length (in bytes) of the data this node represents. For
883         directory nodes, I return the size of the backing store. I return
884         synchronously and do not consult the network, so for mutable objects,
885         I will return the most recently observed size for the object, or None
886         if I don't remember a size. Use get_current_size, which returns a
887         Deferred, if you want more up-to-date information."""
888
889     def get_current_size():
890         """I return a Deferred that fires with the length (in bytes) of the
891         data this node represents.
892         """
893
894
895 class IFileNode(IFilesystemNode):
896     """I am a node which represents a file: a sequence of bytes. I am not a
897     container, like IDirectoryNode."""
898     def get_best_readable_version():
899         """Return a Deferred that fires with an IReadable for the 'best'
900         available version of the file. The IReadable provides only read
901         access, even if this filenode was derived from a write cap.
902
903         For an immutable file, there is only one version. For a mutable
904         file, the 'best' version is the recoverable version with the
905         highest sequence number. If no uncoordinated writes have occurred,
906         and if enough shares are available, then this will be the most
907         recent version that has been uploaded. If no version is recoverable,
908         the Deferred will errback with an UnrecoverableFileError.
909         """
910
911     def download_best_version():
912         """Download the contents of the version that would be returned
913         by get_best_readable_version(). This is equivalent to calling
914         download_to_data() on the IReadable given by that method.
915
916         I return a Deferred that fires with a byte string when the file
917         has been fully downloaded. To support streaming download, use
918         the 'read' method of IReadable. If no version is recoverable,
919         the Deferred will errback with an UnrecoverableFileError.
920         """
921
922     def get_size_of_best_version():
923         """Find the size of the version that would be returned by
924         get_best_readable_version().
925
926         I return a Deferred that fires with an integer. If no version
927         is recoverable, the Deferred will errback with an
928         UnrecoverableFileError.
929         """
930
931
932 class IImmutableFileNode(IFileNode, IReadable):
933     """I am a node representing an immutable file. Immutable files have
934     only one version"""
935
936
937 class IMutableFileNode(IFileNode):
938     """I provide access to a 'mutable file', which retains its identity
939     regardless of what contents are put in it.
940
941     The consistency-vs-availability problem means that there might be
942     multiple versions of a file present in the grid, some of which might be
943     unrecoverable (i.e. have fewer than 'k' shares). These versions are
944     loosely ordered: each has a sequence number and a hash, and any version
945     with seqnum=N was uploaded by a node which has seen at least one version
946     with seqnum=N-1.
947
948     The 'servermap' (an instance of IMutableFileServerMap) is used to
949     describe the versions that are known to be present in the grid, and which
950     servers are hosting their shares. It is used to represent the 'state of
951     the world', and is used for this purpose by my test-and-set operations.
952     Downloading the contents of the mutable file will also return a
953     servermap. Uploading a new version into the mutable file requires a
954     servermap as input, and the semantics of the replace operation is
955     'replace the file with my new version if it looks like nobody else has
956     changed the file since my previous download'. Because the file is
957     distributed, this is not a perfect test-and-set operation, but it will do
958     its best. If the replace process sees evidence of a simultaneous write,
959     it will signal an UncoordinatedWriteError, so that the caller can take
960     corrective action.
961
962
963     Most readers will want to use the 'best' current version of the file, and
964     should use my 'download_best_version()' method.
965
966     To unconditionally replace the file, callers should use overwrite(). This
967     is the mode that user-visible mutable files will probably use.
968
969     To apply some delta to the file, call modify() with a callable modifier
970     function that can apply the modification that you want to make. This is
971     the mode that dirnodes will use, since most directory modification
972     operations can be expressed in terms of deltas to the directory state.
973
974
975     Three methods are available for users who need to perform more complex
976     operations. The first is get_servermap(), which returns an up-to-date
977     servermap using a specified mode. The second is download_version(), which
978     downloads a specific version (not necessarily the 'best' one). The third
979     is 'upload', which accepts new contents and a servermap (which must have
980     been updated with MODE_WRITE). The upload method will attempt to apply
981     the new contents as long as no other node has modified the file since the
982     servermap was updated. This might be useful to a caller who wants to
983     merge multiple versions into a single new one.
984
985     Note that each time the servermap is updated, a specific 'mode' is used,
986     which determines how many peers are queried. To use a servermap for my
987     replace() method, that servermap must have been updated in MODE_WRITE.
988     These modes are defined in allmydata.mutable.common, and consist of
989     MODE_READ, MODE_WRITE, MODE_ANYTHING, and MODE_CHECK. Please look in
990     allmydata/mutable/servermap.py for details about the differences.
991
992     Mutable files are currently limited in size (about 3.5MB max) and can
993     only be retrieved and updated all-at-once, as a single big string. Future
994     versions of our mutable files will remove this restriction.
995     """
996     def get_best_mutable_version():
997         """Return a Deferred that fires with an IMutableFileVersion for
998         the 'best' available version of the file. The best version is
999         the recoverable version with the highest sequence number. If no
1000         uncoordinated writes have occurred, and if enough shares are
1001         available, then this will be the most recent version that has
1002         been uploaded.
1003
1004         If no version is recoverable, the Deferred will errback with an
1005         UnrecoverableFileError.
1006         """
1007
1008     def overwrite(new_contents):
1009         """Unconditionally replace the contents of the mutable file with new
1010         ones. This simply chains get_servermap(MODE_WRITE) and upload(). This
1011         is only appropriate to use when the new contents of the file are
1012         completely unrelated to the old ones, and you do not care about other
1013         clients' changes.
1014
1015         I return a Deferred that fires (with a PublishStatus object) when the
1016         update has completed.
1017         """
1018
1019     def modify(modifier_cb):
1020         """Modify the contents of the file, by downloading the current
1021         version, applying the modifier function (or bound method), then
1022         uploading the new version. I return a Deferred that fires (with a
1023         PublishStatus object) when the update is complete.
1024
1025         The modifier callable will be given three arguments: a string (with
1026         the old contents), a 'first_time' boolean, and a servermap. As with
1027         download_best_version(), the old contents will be from the best
1028         recoverable version, but the modifier can use the servermap to make
1029         other decisions (such as refusing to apply the delta if there are
1030         multiple parallel versions, or if there is evidence of a newer
1031         unrecoverable version). 'first_time' will be True the first time the
1032         modifier is called, and False on any subsequent calls.
1033
1034         The callable should return a string with the new contents. The
1035         callable must be prepared to be called multiple times, and must
1036         examine the input string to see if the change that it wants to make
1037         is already present in the old version. If it does not need to make
1038         any changes, it can either return None, or return its input string.
1039
1040         If the modifier raises an exception, it will be returned in the
1041         errback.
1042         """
1043
1044     def get_servermap(mode):
1045         """Return a Deferred that fires with an IMutableFileServerMap
1046         instance, updated using the given mode.
1047         """
1048
1049     def download_version(servermap, version):
1050         """Download a specific version of the file, using the servermap
1051         as a guide to where the shares are located.
1052
1053         I return a Deferred that fires with the requested contents, or
1054         errbacks with UnrecoverableFileError. Note that a servermap which was
1055         updated with MODE_ANYTHING or MODE_READ may not know about shares for
1056         all versions (those modes stop querying servers as soon as they can
1057         fulfil their goals), so you may want to use MODE_CHECK (which checks
1058         everything) to get increased visibility.
1059         """
1060
1061     def upload(new_contents, servermap):
1062         """Replace the contents of the file with new ones. This requires a
1063         servermap that was previously updated with MODE_WRITE.
1064
1065         I attempt to provide test-and-set semantics, in that I will avoid
1066         modifying any share that is different than the version I saw in the
1067         servermap. However, if another node is writing to the file at the
1068         same time as me, I may manage to update some shares while they update
1069         others. If I see any evidence of this, I will signal
1070         UncoordinatedWriteError, and the file will be left in an inconsistent
1071         state (possibly the version you provided, possibly the old version,
1072         possibly somebody else's version, and possibly a mix of shares from
1073         all of these).
1074
1075         The recommended response to UncoordinatedWriteError is to either
1076         return it to the caller (since they failed to coordinate their
1077         writes), or to attempt some sort of recovery. It may be sufficient to
1078         wait a random interval (with exponential backoff) and repeat your
1079         operation. If I do not signal UncoordinatedWriteError, then I was
1080         able to write the new version without incident.
1081
1082         I return a Deferred that fires (with a PublishStatus object) when the
1083         publish has completed. I will update the servermap in-place with the
1084         location of all new shares.
1085         """
1086
1087     def get_writekey():
1088         """Return this filenode's writekey, or None if the node does not have
1089         write-capability. This may be used to assist with data structures
1090         that need to make certain data available only to writers, such as the
1091         read-write child caps in dirnodes. The recommended process is to have
1092         reader-visible data be submitted to the filenode in the clear (where
1093         it will be encrypted by the filenode using the readkey), but encrypt
1094         writer-visible data using this writekey.
1095         """
1096
1097     def get_version():
1098         """Returns the mutable file protocol version."""
1099
1100
1101 class NotEnoughSharesError(Exception):
1102     """Download was unable to get enough shares"""
1103
1104 class NoSharesError(Exception):
1105     """Download was unable to get any shares at all."""
1106
1107 class DownloadStopped(Exception):
1108     pass
1109
1110 class UploadUnhappinessError(Exception):
1111     """Upload was unable to satisfy 'servers_of_happiness'"""
1112
1113 class UnableToFetchCriticalDownloadDataError(Exception):
1114     """I was unable to fetch some piece of critical data which is supposed to
1115     be identically present in all shares."""
1116
1117 class NoServersError(Exception):
1118     """Upload wasn't given any servers to work with, usually indicating a
1119     network or Introducer problem."""
1120
1121 class ExistingChildError(Exception):
1122     """A directory node was asked to add or replace a child that already
1123     exists, and overwrite= was set to False."""
1124
1125 class NoSuchChildError(Exception):
1126     """A directory node was asked to fetch a child which does not exist."""
1127     def __str__(self):
1128         # avoid UnicodeEncodeErrors when converting to str
1129         return self.__repr__()
1130
1131 class ChildOfWrongTypeError(Exception):
1132     """An operation was attempted on a child of the wrong type (file or directory)."""
1133
1134
1135 class IDirectoryNode(IFilesystemNode):
1136     """I represent a filesystem node that is a container, with a
1137     name-to-child mapping, holding the tahoe equivalent of a directory. All
1138     child names are unicode strings, and all children are some sort of
1139     IFilesystemNode (a file, subdirectory, or unknown node).
1140     """
1141
1142     def get_uri():
1143         """
1144         The dirnode ('1') URI returned by this method can be used in
1145         set_uri() on a different directory ('2') to 'mount' a reference to
1146         this directory ('1') under the other ('2'). This URI is just a
1147         string, so it can be passed around through email or other out-of-band
1148         protocol.
1149         """
1150
1151     def get_readonly_uri():
1152         """
1153         The dirnode ('1') URI returned by this method can be used in
1154         set_uri() on a different directory ('2') to 'mount' a reference to
1155         this directory ('1') under the other ('2'). This URI is just a
1156         string, so it can be passed around through email or other out-of-band
1157         protocol.
1158         """
1159
1160     def list():
1161         """I return a Deferred that fires with a dictionary mapping child
1162         name (a unicode string) to (node, metadata_dict) tuples, in which
1163         'node' is an IFilesystemNode and 'metadata_dict' is a dictionary of
1164         metadata."""
1165
1166     def has_child(name):
1167         """I return a Deferred that fires with a boolean, True if there
1168         exists a child of the given name, False if not. The child name must
1169         be a unicode string."""
1170
1171     def get(name):
1172         """I return a Deferred that fires with a specific named child node,
1173         which is an IFilesystemNode. The child name must be a unicode string.
1174         I raise NoSuchChildError if I do not have a child by that name."""
1175
1176     def get_metadata_for(name):
1177         """I return a Deferred that fires with the metadata dictionary for
1178         a specific named child node. The child name must be a unicode string.
1179         This metadata is stored in the *edge*, not in the child, so it is
1180         attached to the parent dirnode rather than the child node.
1181         I raise NoSuchChildError if I do not have a child by that name."""
1182
1183     def set_metadata_for(name, metadata):
1184         """I replace any existing metadata for the named child with the new
1185         metadata. The child name must be a unicode string. This metadata is
1186         stored in the *edge*, not in the child, so it is attached to the
1187         parent dirnode rather than the child node. I return a Deferred
1188         (that fires with this dirnode) when the operation is complete.
1189         I raise NoSuchChildError if I do not have a child by that name."""
1190
1191     def get_child_at_path(path):
1192         """Transform a child path into an IFilesystemNode.
1193
1194         I perform a recursive series of 'get' operations to find the named
1195         descendant node. I return a Deferred that fires with the node, or
1196         errbacks with NoSuchChildError if the node could not be found.
1197
1198         The path can be either a single string (slash-separated) or a list of
1199         path-name elements. All elements must be unicode strings.
1200         """
1201
1202     def get_child_and_metadata_at_path(path):
1203         """Transform a child path into an IFilesystemNode and metadata.
1204
1205         I am like get_child_at_path(), but my Deferred fires with a tuple of
1206         (node, metadata). The metadata comes from the last edge. If the path
1207         is empty, the metadata will be an empty dictionary.
1208         """
1209
1210     def set_uri(name, writecap, readcap=None, metadata=None, overwrite=True):
1211         """I add a child (by writecap+readcap) at the specific name. I return
1212         a Deferred that fires when the operation finishes. If overwrite= is
1213         True, I will replace any existing child of the same name, otherwise
1214         an existing child will cause me to return ExistingChildError. The
1215         child name must be a unicode string.
1216
1217         The child caps could be for a file, or for a directory. If you have
1218         both the writecap and readcap, you should provide both arguments.
1219         If you have only one cap and don't know whether it is read-only,
1220         provide it as the writecap argument and leave the readcap as None.
1221         If you have only one cap that is known to be read-only, provide it
1222         as the readcap argument and leave the writecap as None.
1223         The filecaps are typically obtained from an IFilesystemNode with
1224         get_uri() and get_readonly_uri().
1225
1226         If metadata= is provided, I will use it as the metadata for the named
1227         edge. This will replace any existing metadata. If metadata= is left
1228         as the default value of None, I will set ['mtime'] to the current
1229         time, and I will set ['ctime'] to the current time if there was not
1230         already a child by this name present. This roughly matches the
1231         ctime/mtime semantics of traditional filesystems.  See the
1232         "About the metadata" section of webapi.txt for futher information.
1233
1234         If this directory node is read-only, the Deferred will errback with a
1235         NotWriteableError."""
1236
1237     def set_children(entries, overwrite=True):
1238         """Add multiple children (by writecap+readcap) to a directory node.
1239         Takes a dictionary, with childname as keys and (writecap, readcap)
1240         tuples (or (writecap, readcap, metadata) triples) as values. Returns
1241         a Deferred that fires (with this dirnode) when the operation
1242         finishes. This is equivalent to calling set_uri() multiple times, but
1243         is much more efficient. All child names must be unicode strings.
1244         """
1245
1246     def set_node(name, child, metadata=None, overwrite=True):
1247         """I add a child at the specific name. I return a Deferred that fires
1248         when the operation finishes. This Deferred will fire with the child
1249         node that was just added. I will replace any existing child of the
1250         same name. The child name must be a unicode string. The 'child'
1251         instance must be an instance providing IFilesystemNode.
1252
1253         If metadata= is provided, I will use it as the metadata for the named
1254         edge. This will replace any existing metadata. If metadata= is left
1255         as the default value of None, I will set ['mtime'] to the current
1256         time, and I will set ['ctime'] to the current time if there was not
1257         already a child by this name present. This roughly matches the
1258         ctime/mtime semantics of traditional filesystems. See the
1259         "About the metadata" section of webapi.txt for futher information.
1260
1261         If this directory node is read-only, the Deferred will errback with a
1262         NotWriteableError."""
1263
1264     def set_nodes(entries, overwrite=True):
1265         """Add multiple children to a directory node. Takes a dict mapping
1266         unicode childname to (child_node, metdata) tuples. If metdata=None,
1267         the original metadata is left unmodified. Returns a Deferred that
1268         fires (with this dirnode) when the operation finishes. This is
1269         equivalent to calling set_node() multiple times, but is much more
1270         efficient."""
1271
1272     def add_file(name, uploadable, metadata=None, overwrite=True):
1273         """I upload a file (using the given IUploadable), then attach the
1274         resulting ImmutableFileNode to the directory at the given name. I set
1275         metadata the same way as set_uri and set_node. The child name must be
1276         a unicode string.
1277
1278         I return a Deferred that fires (with the IFileNode of the uploaded
1279         file) when the operation completes."""
1280
1281     def delete(name, must_exist=True, must_be_directory=False, must_be_file=False):
1282         """I remove the child at the specific name. I return a Deferred that
1283         fires when the operation finishes. The child name must be a unicode
1284         string. If must_exist is True and I do not have a child by that name,
1285         I raise NoSuchChildError. If must_be_directory is True and the child
1286         is a file, or if must_be_file is True and the child is a directory,
1287         I raise ChildOfWrongTypeError."""
1288
1289     def create_subdirectory(name, initial_children={}, overwrite=True, metadata=None):
1290         """I create and attach a directory at the given name. The new
1291         directory can be empty, or it can be populated with children
1292         according to 'initial_children', which takes a dictionary in the same
1293         format as set_nodes (i.e. mapping unicode child name to (childnode,
1294         metadata) tuples). The child name must be a unicode string. I return
1295         a Deferred that fires (with the new directory node) when the
1296         operation finishes."""
1297
1298     def move_child_to(current_child_name, new_parent, new_child_name=None,
1299                       overwrite=True):
1300         """I take one of my children and move them to a new parent. The child
1301         is referenced by name. On the new parent, the child will live under
1302         'new_child_name', which defaults to 'current_child_name'. TODO: what
1303         should we do about metadata? I return a Deferred that fires when the
1304         operation finishes. The child name must be a unicode string. I raise
1305         NoSuchChildError if I do not have a child by that name."""
1306
1307     def build_manifest():
1308         """I generate a table of everything reachable from this directory.
1309         I also compute deep-stats as described below.
1310
1311         I return a Monitor. The Monitor's results will be a dictionary with
1312         four elements:
1313
1314          res['manifest']: a list of (path, cap) tuples for all nodes
1315                           (directories and files) reachable from this one.
1316                           'path' will be a tuple of unicode strings. The
1317                           origin dirnode will be represented by an empty path
1318                           tuple.
1319          res['verifycaps']: a list of (printable) verifycap strings, one for
1320                             each reachable non-LIT node. This is a set:
1321                             it will contain no duplicates.
1322          res['storage-index']: a list of (base32) storage index strings,
1323                                one for each reachable non-LIT node. This is
1324                                a set: it will contain no duplicates.
1325          res['stats']: a dictionary, the same that is generated by
1326                        start_deep_stats() below.
1327
1328         The Monitor will also have an .origin_si attribute with the (binary)
1329         storage index of the starting point.
1330         """
1331
1332     def start_deep_stats():
1333         """Return a Monitor, examining all nodes (directories and files)
1334         reachable from this one. The Monitor's results will be a dictionary
1335         with the following keys::
1336
1337            count-immutable-files: count of how many CHK files are in the set
1338            count-mutable-files: same, for mutable files (does not include
1339                                 directories)
1340            count-literal-files: same, for LIT files
1341            count-files: sum of the above three
1342
1343            count-directories: count of directories
1344
1345            size-immutable-files: total bytes for all CHK files in the set
1346            size-mutable-files (TODO): same, for current version of all mutable
1347                                       files, does not include directories
1348            size-literal-files: same, for LIT files
1349            size-directories: size of mutable files used by directories
1350
1351            largest-directory: number of bytes in the largest directory
1352            largest-directory-children: number of children in the largest
1353                                        directory
1354            largest-immutable-file: number of bytes in the largest CHK file
1355
1356         size-mutable-files is not yet implemented, because it would involve
1357         even more queries than deep_stats does.
1358
1359         The Monitor will also have an .origin_si attribute with the (binary)
1360         storage index of the starting point.
1361
1362         This operation will visit every directory node underneath this one,
1363         and can take a long time to run. On a typical workstation with good
1364         bandwidth, this can examine roughly 15 directories per second (and
1365         takes several minutes of 100% CPU for ~1700 directories).
1366         """
1367
1368
1369 class ICodecEncoder(Interface):
1370     def set_params(data_size, required_shares, max_shares):
1371         """Set up the parameters of this encoder.
1372
1373         This prepares the encoder to perform an operation that converts a
1374         single block of data into a number of shares, such that a future
1375         ICodecDecoder can use a subset of these shares to recover the
1376         original data. This operation is invoked by calling encode(). Once
1377         the encoding parameters are set up, the encode operation can be
1378         invoked multiple times.
1379
1380         set_params() prepares the encoder to accept blocks of input data that
1381         are exactly 'data_size' bytes in length. The encoder will be prepared
1382         to produce 'max_shares' shares for each encode() operation (although
1383         see the 'desired_share_ids' to use less CPU). The encoding math will
1384         be chosen such that the decoder can get by with as few as
1385         'required_shares' of these shares and still reproduce the original
1386         data. For example, set_params(1000, 5, 5) offers no redundancy at
1387         all, whereas set_params(1000, 1, 10) provides 10x redundancy.
1388
1389         Numerical Restrictions: 'data_size' is required to be an integral
1390         multiple of 'required_shares'. In general, the caller should choose
1391         required_shares and max_shares based upon their reliability
1392         requirements and the number of peers available (the total storage
1393         space used is roughly equal to max_shares*data_size/required_shares),
1394         then choose data_size to achieve the memory footprint desired (larger
1395         data_size means more efficient operation, smaller data_size means
1396         smaller memory footprint).
1397
1398         In addition, 'max_shares' must be equal to or greater than
1399         'required_shares'. Of course, setting them to be equal causes
1400         encode() to degenerate into a particularly slow form of the 'split'
1401         utility.
1402
1403         See encode() for more details about how these parameters are used.
1404
1405         set_params() must be called before any other ICodecEncoder methods
1406         may be invoked.
1407         """
1408
1409     def get_params():
1410         """Return the 3-tuple of data_size, required_shares, max_shares"""
1411
1412     def get_encoder_type():
1413         """Return a short string that describes the type of this encoder.
1414
1415         There is required to be a global table of encoder classes. This method
1416         returns an index into this table; the value at this index is an
1417         encoder class, and this encoder is an instance of that class.
1418         """
1419
1420     def get_block_size():
1421         """Return the length of the shares that encode() will produce.
1422         """
1423
1424     def encode_proposal(data, desired_share_ids=None):
1425         """Encode some data.
1426
1427         'data' must be a string (or other buffer object), and len(data) must
1428         be equal to the 'data_size' value passed earlier to set_params().
1429
1430         This will return a Deferred that will fire with two lists. The first
1431         is a list of shares, each of which is a string (or other buffer
1432         object) such that len(share) is the same as what get_share_size()
1433         returned earlier. The second is a list of shareids, in which each is
1434         an integer. The lengths of the two lists will always be equal to each
1435         other. The user should take care to keep each share closely
1436         associated with its shareid, as one is useless without the other.
1437
1438         The length of this output list will normally be the same as the value
1439         provided to the 'max_shares' parameter of set_params(). This may be
1440         different if 'desired_share_ids' is provided.
1441
1442         'desired_share_ids', if provided, is required to be a sequence of
1443         ints, each of which is required to be >= 0 and < max_shares. If not
1444         provided, encode() will produce 'max_shares' shares, as if
1445         'desired_share_ids' were set to range(max_shares). You might use this
1446         if you initially thought you were going to use 10 peers, started
1447         encoding, and then two of the peers dropped out: you could use
1448         desired_share_ids= to skip the work (both memory and CPU) of
1449         producing shares for the peers which are no longer available.
1450
1451         """
1452
1453     def encode(inshares, desired_share_ids=None):
1454         """Encode some data. This may be called multiple times. Each call is
1455         independent.
1456
1457         inshares is a sequence of length required_shares, containing buffers
1458         (i.e. strings), where each buffer contains the next contiguous
1459         non-overlapping segment of the input data. Each buffer is required to
1460         be the same length, and the sum of the lengths of the buffers is
1461         required to be exactly the data_size promised by set_params(). (This
1462         implies that the data has to be padded before being passed to
1463         encode(), unless of course it already happens to be an even multiple
1464         of required_shares in length.)
1465
1466         Note: the requirement to break up your data into
1467         'required_shares' chunks of exactly the right length before
1468         calling encode() is surprising from point of view of a user
1469         who doesn't know how FEC works. It feels like an
1470         implementation detail that has leaked outside the abstraction
1471         barrier. Is there a use case in which the data to be encoded
1472         might already be available in pre-segmented chunks, such that
1473         it is faster or less work to make encode() take a list rather
1474         than splitting a single string?
1475
1476         Yes, there is: suppose you are uploading a file with K=64,
1477         N=128, segsize=262,144. Then each in-share will be of size
1478         4096. If you use this .encode() API then your code could first
1479         read each successive 4096-byte chunk from the file and store
1480         each one in a Python string and store each such Python string
1481         in a Python list. Then you could call .encode(), passing that
1482         list as "inshares". The encoder would generate the other 64
1483         "secondary shares" and return to you a new list containing
1484         references to the same 64 Python strings that you passed in
1485         (as the primary shares) plus references to the new 64 Python
1486         strings.
1487
1488         (You could even imagine that your code could use readv() so
1489         that the operating system can arrange to get all of those
1490         bytes copied from the file into the Python list of Python
1491         strings as efficiently as possible instead of having a loop
1492         written in C or in Python to copy the next part of the file
1493         into the next string.)
1494
1495         On the other hand if you instead use the .encode_proposal()
1496         API (above), then your code can first read in all of the
1497         262,144 bytes of the segment from the file into a Python
1498         string, then call .encode_proposal() passing the segment data
1499         as the "data" argument. The encoder would basically first
1500         split the "data" argument into a list of 64 in-shares of 4096
1501         byte each, and then do the same thing that .encode() does. So
1502         this would result in a little bit more copying of data and a
1503         little bit higher of a "maximum memory usage" during the
1504         process, although it might or might not make a practical
1505         difference for our current use cases.
1506
1507         Note that "inshares" is a strange name for the parameter if
1508         you think of the parameter as being just for feeding in data
1509         to the codec. It makes more sense if you think of the result
1510         of this encoding as being the set of shares from inshares plus
1511         an extra set of "secondary shares" (or "check shares"). It is
1512         a surprising name! If the API is going to be surprising then
1513         the name should be surprising. If we switch to
1514         encode_proposal() above then we should also switch to an
1515         unsurprising name.
1516
1517         'desired_share_ids', if provided, is required to be a sequence of
1518         ints, each of which is required to be >= 0 and < max_shares. If not
1519         provided, encode() will produce 'max_shares' shares, as if
1520         'desired_share_ids' were set to range(max_shares). You might use this
1521         if you initially thought you were going to use 10 peers, started
1522         encoding, and then two of the peers dropped out: you could use
1523         desired_share_ids= to skip the work (both memory and CPU) of
1524         producing shares for the peers which are no longer available.
1525
1526         For each call, encode() will return a Deferred that fires with two
1527         lists, one containing shares and the other containing the shareids.
1528         The get_share_size() method can be used to determine the length of
1529         the share strings returned by encode(). Each shareid is a small
1530         integer, exactly as passed into 'desired_share_ids' (or
1531         range(max_shares), if desired_share_ids was not provided).
1532
1533         The shares and their corresponding shareids are required to be kept
1534         together during storage and retrieval. Specifically, the share data is
1535         useless by itself: the decoder needs to be told which share is which
1536         by providing it with both the shareid and the actual share data.
1537
1538         This function will allocate an amount of memory roughly equal to::
1539
1540          (max_shares - required_shares) * get_share_size()
1541
1542         When combined with the memory that the caller must allocate to
1543         provide the input data, this leads to a memory footprint roughly
1544         equal to the size of the resulting encoded shares (i.e. the expansion
1545         factor times the size of the input segment).
1546         """
1547
1548         # rejected ideas:
1549         #
1550         #  returning a list of (shareidN,shareN) tuples instead of a pair of
1551         #  lists (shareids..,shares..). Brian thought the tuples would
1552         #  encourage users to keep the share and shareid together throughout
1553         #  later processing, Zooko pointed out that the code to iterate
1554         #  through two lists is not really more complicated than using a list
1555         #  of tuples and there's also a performance improvement
1556         #
1557         #  having 'data_size' not required to be an integral multiple of
1558         #  'required_shares'. Doing this would require encode() to perform
1559         #  padding internally, and we'd prefer to have any padding be done
1560         #  explicitly by the caller. Yes, it is an abstraction leak, but
1561         #  hopefully not an onerous one.
1562
1563
1564 class ICodecDecoder(Interface):
1565     def set_params(data_size, required_shares, max_shares):
1566         """Set the params. They have to be exactly the same ones that were
1567         used for encoding."""
1568
1569     def get_needed_shares():
1570         """Return the number of shares needed to reconstruct the data.
1571         set_params() is required to be called before this."""
1572
1573     def decode(some_shares, their_shareids):
1574         """Decode a partial list of shares into data.
1575
1576         'some_shares' is required to be a sequence of buffers of sharedata, a
1577         subset of the shares returned by ICodecEncode.encode(). Each share is
1578         required to be of the same length.  The i'th element of their_shareids
1579         is required to be the shareid of the i'th buffer in some_shares.
1580
1581         This returns a Deferred which fires with a sequence of buffers. This
1582         sequence will contain all of the segments of the original data, in
1583         order. The sum of the lengths of all of the buffers will be the
1584         'data_size' value passed into the original ICodecEncode.set_params()
1585         call. To get back the single original input block of data, use
1586         ''.join(output_buffers), or you may wish to simply write them in
1587         order to an output file.
1588
1589         Note that some of the elements in the result sequence may be
1590         references to the elements of the some_shares input sequence. In
1591         particular, this means that if those share objects are mutable (e.g.
1592         arrays) and if they are changed, then both the input (the
1593         'some_shares' parameter) and the output (the value given when the
1594         deferred is triggered) will change.
1595
1596         The length of 'some_shares' is required to be exactly the value of
1597         'required_shares' passed into the original ICodecEncode.set_params()
1598         call.
1599         """
1600
1601
1602 class IEncoder(Interface):
1603     """I take an object that provides IEncryptedUploadable, which provides
1604     encrypted data, and a list of shareholders. I then encode, hash, and
1605     deliver shares to those shareholders. I will compute all the necessary
1606     Merkle hash trees that are necessary to validate the crypttext that
1607     eventually comes back from the shareholders. I provide the URI Extension
1608     Block Hash, and the encoding parameters, both of which must be included
1609     in the URI.
1610
1611     I do not choose shareholders, that is left to the IUploader. I must be
1612     given a dict of RemoteReferences to storage buckets that are ready and
1613     willing to receive data.
1614     """
1615
1616     def set_size(size):
1617         """Specify the number of bytes that will be encoded. This must be
1618         peformed before get_serialized_params() can be called.
1619         """
1620     def set_params(params):
1621         """Override the default encoding parameters. 'params' is a tuple of
1622         (k,d,n), where 'k' is the number of required shares, 'd' is the
1623         servers_of_happiness, and 'n' is the total number of shares that will
1624         be created.
1625
1626         Encoding parameters can be set in three ways. 1: The Encoder class
1627         provides defaults (3/7/10). 2: the Encoder can be constructed with
1628         an 'options' dictionary, in which the
1629         needed_and_happy_and_total_shares' key can be a (k,d,n) tuple. 3:
1630         set_params((k,d,n)) can be called.
1631
1632         If you intend to use set_params(), you must call it before
1633         get_share_size or get_param are called.
1634         """
1635
1636     def set_encrypted_uploadable(u):
1637         """Provide a source of encrypted upload data. 'u' must implement
1638         IEncryptedUploadable.
1639
1640         When this is called, the IEncryptedUploadable will be queried for its
1641         length and the storage_index that should be used.
1642
1643         This returns a Deferred that fires with this Encoder instance.
1644
1645         This must be performed before start() can be called.
1646         """
1647
1648     def get_param(name):
1649         """Return an encoding parameter, by name.
1650
1651         'storage_index': return a string with the (16-byte truncated SHA-256
1652                          hash) storage index to which these shares should be
1653                          pushed.
1654
1655         'share_counts': return a tuple describing how many shares are used:
1656                         (needed_shares, servers_of_happiness, total_shares)
1657
1658         'num_segments': return an int with the number of segments that
1659                         will be encoded.
1660
1661         'segment_size': return an int with the size of each segment.
1662
1663         'block_size': return the size of the individual blocks that will
1664                       be delivered to a shareholder's put_block() method. By
1665                       knowing this, the shareholder will be able to keep all
1666                       blocks in a single file and still provide random access
1667                       when reading them. # TODO: can we avoid exposing this?
1668
1669         'share_size': an int with the size of the data that will be stored
1670                       on each shareholder. This is aggregate amount of data
1671                       that will be sent to the shareholder, summed over all
1672                       the put_block() calls I will ever make. It is useful to
1673                       determine this size before asking potential
1674                       shareholders whether they will grant a lease or not,
1675                       since their answers will depend upon how much space we
1676                       need. TODO: this might also include some amount of
1677                       overhead, like the size of all the hashes. We need to
1678                       decide whether this is useful or not.
1679
1680         'serialized_params': a string with a concise description of the
1681                              codec name and its parameters. This may be passed
1682                              into the IUploadable to let it make sure that
1683                              the same file encoded with different parameters
1684                              will result in different storage indexes.
1685
1686         Once this is called, set_size() and set_params() may not be called.
1687         """
1688
1689     def set_shareholders(shareholders, servermap):
1690         """Tell the encoder where to put the encoded shares. 'shareholders'
1691         must be a dictionary that maps share number (an integer ranging from
1692         0 to n-1) to an instance that provides IStorageBucketWriter.
1693         'servermap' is a dictionary that maps share number (as defined above)
1694         to a set of peerids. This must be performed before start() can be
1695         called."""
1696
1697     def start():
1698         """Begin the encode/upload process. This involves reading encrypted
1699         data from the IEncryptedUploadable, encoding it, uploading the shares
1700         to the shareholders, then sending the hash trees.
1701
1702         set_encrypted_uploadable() and set_shareholders() must be called
1703         before this can be invoked.
1704
1705         This returns a Deferred that fires with a verify cap when the upload
1706         process is complete. The verifycap, plus the encryption key, is
1707         sufficient to construct the read cap.
1708         """
1709
1710
1711 class IDecoder(Interface):
1712     """I take a list of shareholders and some setup information, then
1713     download, validate, decode, and decrypt data from them, writing the
1714     results to an output file.
1715
1716     I do not locate the shareholders, that is left to the IDownloader. I must
1717     be given a dict of RemoteReferences to storage buckets that are ready to
1718     send data.
1719     """
1720
1721     def setup(outfile):
1722         """I take a file-like object (providing write and close) to which all
1723         the plaintext data will be written.
1724
1725         TODO: producer/consumer . Maybe write() should return a Deferred that
1726         indicates when it will accept more data? But probably having the
1727         IDecoder be a producer is easier to glue to IConsumer pieces.
1728         """
1729
1730     def set_shareholders(shareholders):
1731         """I take a dictionary that maps share identifiers (small integers)
1732         to RemoteReferences that provide RIBucketReader. This must be called
1733         before start()."""
1734
1735     def start():
1736         """I start the download. This process involves retrieving data and
1737         hash chains from the shareholders, using the hashes to validate the
1738         data, decoding the shares into segments, decrypting the segments,
1739         then writing the resulting plaintext to the output file.
1740
1741         I return a Deferred that will fire (with self) when the download is
1742         complete.
1743         """
1744
1745
1746 class IDownloadTarget(Interface):
1747     # Note that if the IDownloadTarget is also an IConsumer, the downloader
1748     # will register itself as a producer. This allows the target to invoke
1749     # downloader.pauseProducing, resumeProducing, and stopProducing.
1750     def open(size):
1751         """Called before any calls to write() or close(). If an error
1752         occurs before any data is available, fail() may be called without
1753         a previous call to open().
1754
1755         'size' is the length of the file being downloaded, in bytes."""
1756
1757     def write(data):
1758         """Output some data to the target."""
1759
1760     def close():
1761         """Inform the target that there is no more data to be written."""
1762
1763     def fail(why):
1764         """fail() is called to indicate that the download has failed. 'why'
1765         is a Failure object indicating what went wrong. No further methods
1766         will be invoked on the IDownloadTarget after fail()."""
1767
1768     def register_canceller(cb):
1769         """The CiphertextDownloader uses this to register a no-argument function
1770         that the target can call to cancel the download. Once this canceller
1771         is invoked, no further calls to write() or close() will be made."""
1772
1773     def finish():
1774         """When the CiphertextDownloader is done, this finish() function will be
1775         called. Whatever it returns will be returned to the invoker of
1776         Downloader.download.
1777         """
1778
1779
1780 class IDownloader(Interface):
1781     def download(uri, target):
1782         """Perform a CHK download, sending the data to the given target.
1783         'target' must provide IDownloadTarget.
1784
1785         Returns a Deferred that fires (with the results of target.finish)
1786         when the download is finished, or errbacks if something went wrong."""
1787
1788
1789 class IEncryptedUploadable(Interface):
1790     def set_upload_status(upload_status):
1791         """Provide an IUploadStatus object that should be filled with status
1792         information. The IEncryptedUploadable is responsible for setting
1793         key-determination progress ('chk'), size, storage_index, and
1794         ciphertext-fetch progress. It may delegate some of this
1795         responsibility to others, in particular to the IUploadable."""
1796
1797     def get_size():
1798         """This behaves just like IUploadable.get_size()."""
1799
1800     def get_all_encoding_parameters():
1801         """Return a Deferred that fires with a tuple of
1802         (k,happy,n,segment_size). The segment_size will be used as-is, and
1803         must match the following constraints: it must be a multiple of k, and
1804         it shouldn't be unreasonably larger than the file size (if
1805         segment_size is larger than filesize, the difference must be stored
1806         as padding).
1807
1808         This usually passes through to the IUploadable method of the same
1809         name.
1810
1811         The encoder strictly obeys the values returned by this method. To
1812         make an upload use non-default encoding parameters, you must arrange
1813         to control the values that this method returns.
1814         """
1815
1816     def get_storage_index():
1817         """Return a Deferred that fires with a 16-byte storage index.
1818         """
1819
1820     def read_encrypted(length, hash_only):
1821         """This behaves just like IUploadable.read(), but returns crypttext
1822         instead of plaintext. If hash_only is True, then this discards the
1823         data (and returns an empty list); this improves efficiency when
1824         resuming an interrupted upload (where we need to compute the
1825         plaintext hashes, but don't need the redundant encrypted data)."""
1826
1827     def get_plaintext_hashtree_leaves(first, last, num_segments):
1828         """OBSOLETE; Get the leaf nodes of a merkle hash tree over the
1829         plaintext segments, i.e. get the tagged hashes of the given segments.
1830         The segment size is expected to be generated by the
1831         IEncryptedUploadable before any plaintext is read or ciphertext
1832         produced, so that the segment hashes can be generated with only a
1833         single pass.
1834
1835         This returns a Deferred which fires with a sequence of hashes, using:
1836
1837          tuple(segment_hashes[first:last])
1838
1839         'num_segments' is used to assert that the number of segments that the
1840         IEncryptedUploadable handled matches the number of segments that the
1841         encoder was expecting.
1842
1843         This method must not be called until the final byte has been read
1844         from read_encrypted(). Once this method is called, read_encrypted()
1845         can never be called again.
1846         """
1847
1848     def get_plaintext_hash():
1849         """OBSOLETE; Get the hash of the whole plaintext.
1850
1851         This returns a Deferred which fires with a tagged SHA-256 hash of the
1852         whole plaintext, obtained from hashutil.plaintext_hash(data).
1853         """
1854
1855     def close():
1856         """Just like IUploadable.close()."""
1857
1858
1859 class IUploadable(Interface):
1860     def set_upload_status(upload_status):
1861         """Provide an IUploadStatus object that should be filled with status
1862         information. The IUploadable is responsible for setting
1863         key-determination progress ('chk')."""
1864
1865     def set_default_encoding_parameters(params):
1866         """Set the default encoding parameters, which must be a dict mapping
1867         strings to ints. The meaningful keys are 'k', 'happy', 'n', and
1868         'max_segment_size'. These might have an influence on the final
1869         encoding parameters returned by get_all_encoding_parameters(), if the
1870         Uploadable doesn't have more specific preferences.
1871
1872         This call is optional: if it is not used, the Uploadable will use
1873         some built-in defaults. If used, this method must be called before
1874         any other IUploadable methods to have any effect.
1875         """
1876
1877     def get_size():
1878         """Return a Deferred that will fire with the length of the data to be
1879         uploaded, in bytes. This will be called before the data is actually
1880         used, to compute encoding parameters.
1881         """
1882
1883     def get_all_encoding_parameters():
1884         """Return a Deferred that fires with a tuple of
1885         (k,happy,n,segment_size). The segment_size will be used as-is, and
1886         must match the following constraints: it must be a multiple of k, and
1887         it shouldn't be unreasonably larger than the file size (if
1888         segment_size is larger than filesize, the difference must be stored
1889         as padding).
1890
1891         The relative values of k and n allow some IUploadables to request
1892         better redundancy than others (in exchange for consuming more space
1893         in the grid).
1894
1895         Larger values of segment_size reduce hash overhead, while smaller
1896         values reduce memory footprint and cause data to be delivered in
1897         smaller pieces (which may provide a smoother and more predictable
1898         download experience).
1899
1900         The encoder strictly obeys the values returned by this method. To
1901         make an upload use non-default encoding parameters, you must arrange
1902         to control the values that this method returns. One way to influence
1903         them may be to call set_encoding_parameters() before calling
1904         get_all_encoding_parameters().
1905         """
1906
1907     def get_encryption_key():
1908         """Return a Deferred that fires with a 16-byte AES key. This key will
1909         be used to encrypt the data. The key will also be hashed to derive
1910         the StorageIndex.
1911
1912         Uploadables which want to achieve convergence should hash their file
1913         contents and the serialized_encoding_parameters to form the key
1914         (which of course requires a full pass over the data). Uploadables can
1915         use the upload.ConvergentUploadMixin class to achieve this
1916         automatically.
1917
1918         Uploadables which do not care about convergence (or do not wish to
1919         make multiple passes over the data) can simply return a
1920         strongly-random 16 byte string.
1921
1922         get_encryption_key() may be called multiple times: the IUploadable is
1923         required to return the same value each time.
1924         """
1925
1926     def read(length):
1927         """Return a Deferred that fires with a list of strings (perhaps with
1928         only a single element) which, when concatenated together, contain the
1929         next 'length' bytes of data. If EOF is near, this may provide fewer
1930         than 'length' bytes. The total number of bytes provided by read()
1931         before it signals EOF must equal the size provided by get_size().
1932
1933         If the data must be acquired through multiple internal read
1934         operations, returning a list instead of a single string may help to
1935         reduce string copies. However, the length of the concatenated strings
1936         must equal the amount of data requested, unless EOF is encountered.
1937         Long reads, or short reads without EOF, are not allowed. read()
1938         should return the same amount of data as a local disk file read, just
1939         in a different shape and asynchronously.
1940
1941         'length' will typically be equal to (min(get_size(),1MB)/req_shares),
1942         so a 10kB file means length=3kB, 100kB file means length=30kB,
1943         and >=1MB file means length=300kB.
1944
1945         This method provides for a single full pass through the data. Later
1946         use cases may desire multiple passes or access to only parts of the
1947         data (such as a mutable file making small edits-in-place). This API
1948         will be expanded once those use cases are better understood.
1949         """
1950
1951     def close():
1952         """The upload is finished, and whatever filehandle was in use may be
1953         closed."""
1954
1955
1956 class IMutableUploadable(Interface):
1957     """
1958     I represent content that is due to be uploaded to a mutable filecap.
1959     """
1960     # This is somewhat simpler than the IUploadable interface above
1961     # because mutable files do not need to be concerned with possibly
1962     # generating a CHK, nor with per-file keys. It is a subset of the
1963     # methods in IUploadable, though, so we could just as well implement
1964     # the mutable uploadables as IUploadables that don't happen to use
1965     # those methods (with the understanding that the unused methods will
1966     # never be called on such objects)
1967     def get_size():
1968         """
1969         Returns a Deferred that fires with the size of the content held
1970         by the uploadable.
1971         """
1972
1973     def read(length):
1974         """
1975         Returns a list of strings which, when concatenated, are the next
1976         length bytes of the file, or fewer if there are fewer bytes
1977         between the current location and the end of the file.
1978         """
1979
1980     def close():
1981         """
1982         The process that used the Uploadable is finished using it, so
1983         the uploadable may be closed.
1984         """
1985
1986
1987 class IUploadResults(Interface):
1988     """I am returned by immutable upload() methods and contain the results of
1989     the upload.
1990
1991     Note that some of my methods return empty values (0 or an empty dict)
1992     when called for non-distributed LIT files."""
1993
1994     def get_file_size():
1995         """Return the file size, in bytes."""
1996
1997     def get_uri():
1998         """Return the (string) URI of the object uploaded, a CHK readcap."""
1999
2000     def get_ciphertext_fetched():
2001         """Return the number of bytes fetched by the helpe for this upload,
2002         or 0 if the helper did not need to fetch any bytes (or if there was
2003         no helper)."""
2004
2005     def get_preexisting_shares():
2006         """Return the number of shares that were already present in the grid."""
2007
2008     def get_pushed_shares():
2009         """Return the number of shares that were uploaded."""
2010
2011     def get_sharemap():
2012         """Return a dict mapping share identifier to set of IServer
2013         instances. This indicates which servers were given which shares. For
2014         immutable files, the shareid is an integer (the share number, from 0
2015         to N-1). For mutable files, it is a string of the form
2016         'seq%d-%s-sh%d', containing the sequence number, the roothash, and
2017         the share number."""
2018
2019     def get_servermap():
2020         """Return dict mapping IServer instance to a set of share numbers."""
2021
2022     def get_timings():
2023         """Return dict of timing information, mapping name to seconds. All
2024         times are floats:
2025           total : total upload time, start to finish
2026           storage_index : time to compute the storage index
2027           peer_selection : time to decide which peers will be used
2028           contacting_helper : initial helper query to upload/no-upload decision
2029           helper_total : initial helper query to helper finished pushing
2030           cumulative_fetch : helper waiting for ciphertext requests
2031           total_fetch : helper start to last ciphertext response
2032           cumulative_encoding : just time spent in zfec
2033           cumulative_sending : just time spent waiting for storage servers
2034           hashes_and_close : last segment push to shareholder close
2035           total_encode_and_push : first encode to shareholder close
2036         """
2037
2038     def get_uri_extension_data():
2039         """Return the dict of UEB data created for this file."""
2040
2041     def get_verifycapstr():
2042         """Return the (string) verify-cap URI for the uploaded object."""
2043
2044
2045 class IDownloadResults(Interface):
2046     """I am created internally by download() methods. I contain a number of
2047     public attributes which contain details about the download process.::
2048
2049      .file_size : the size of the file, in bytes
2050      .servers_used : set of server peerids that were used during download
2051      .server_problems : dict mapping server peerid to a problem string. Only
2052                         servers that had problems (bad hashes, disconnects)
2053                         are listed here.
2054      .servermap : dict mapping server peerid to a set of share numbers. Only
2055                   servers that had any shares are listed here.
2056      .timings : dict of timing information, mapping name to seconds (float)
2057        peer_selection : time to ask servers about shares
2058        servers_peer_selection : dict of peerid to DYHB-query time
2059        uri_extension : time to fetch a copy of the URI extension block
2060        hashtrees : time to fetch the hash trees
2061        segments : time to fetch, decode, and deliver segments
2062        cumulative_fetch : time spent waiting for storage servers
2063        cumulative_decode : just time spent in zfec
2064        cumulative_decrypt : just time spent in decryption
2065        total : total download time, start to finish
2066        fetch_per_server : dict of server to list of per-segment fetch times
2067     """
2068
2069
2070 class IUploader(Interface):
2071     def upload(uploadable):
2072         """Upload the file. 'uploadable' must impement IUploadable. This
2073         returns a Deferred which fires with an IUploadResults instance, from
2074         which the URI of the file can be obtained as results.uri ."""
2075
2076     def upload_ssk(write_capability, new_version, uploadable):
2077         """TODO: how should this work?"""
2078
2079 class ICheckable(Interface):
2080     def check(monitor, verify=False, add_lease=False):
2081         """Check up on my health, optionally repairing any problems.
2082
2083         This returns a Deferred that fires with an instance that provides
2084         ICheckResults, or None if the object is non-distributed (i.e. LIT
2085         files).
2086
2087         The monitor will be checked periodically to see if the operation has
2088         been cancelled. If so, no new queries will be sent, and the Deferred
2089         will fire (with a OperationCancelledError) immediately.
2090
2091         Filenodes and dirnodes (which provide IFilesystemNode) are also
2092         checkable. Instances that represent verifier-caps will be checkable
2093         but not downloadable. Some objects (like LIT files) do not actually
2094         live in the grid, and their checkers return None (non-distributed
2095         files are always healthy).
2096
2097         If verify=False, a relatively lightweight check will be performed: I
2098         will ask all servers if they have a share for me, and I will believe
2099         whatever they say. If there are at least N distinct shares on the
2100         grid, my results will indicate r.is_healthy()==True. This requires a
2101         roundtrip to each server, but does not transfer very much data, so
2102         the network bandwidth is fairly low.
2103
2104         If verify=True, a more resource-intensive check will be performed:
2105         every share will be downloaded, and the hashes will be validated on
2106         every bit. I will ignore any shares that failed their hash checks. If
2107         there are at least N distinct valid shares on the grid, my results
2108         will indicate r.is_healthy()==True. This requires N/k times as much
2109         download bandwidth (and server disk IO) as a regular download. If a
2110         storage server is holding a corrupt share, or is experiencing memory
2111         failures during retrieval, or is malicious or buggy, then
2112         verification will detect the problem, but checking will not.
2113
2114         If add_lease=True, I will ensure that an up-to-date lease is present
2115         on each share. The lease secrets will be derived from by node secret
2116         (in BASEDIR/private/secret), so either I will add a new lease to the
2117         share, or I will merely renew the lease that I already had. In a
2118         future version of the storage-server protocol (once Accounting has
2119         been implemented), there may be additional options here to define the
2120         kind of lease that is obtained (which account number to claim, etc).
2121
2122         TODO: any problems seen during checking will be reported to the
2123         health-manager.furl, a centralized object which is responsible for
2124         figuring out why files are unhealthy so corrective action can be
2125         taken.
2126         """
2127
2128     def check_and_repair(monitor, verify=False, add_lease=False):
2129         """Like check(), but if the file/directory is not healthy, attempt to
2130         repair the damage.
2131
2132         Any non-healthy result will cause an immediate repair operation, to
2133         generate and upload new shares. After repair, the file will be as
2134         healthy as we can make it. Details about what sort of repair is done
2135         will be put in the check-and-repair results. The Deferred will not
2136         fire until the repair is complete.
2137
2138         This returns a Deferred which fires with an instance of
2139         ICheckAndRepairResults."""
2140
2141
2142 class IDeepCheckable(Interface):
2143     def start_deep_check(verify=False, add_lease=False):
2144         """Check upon the health of me and everything I can reach.
2145
2146         This is a recursive form of check(), useable only on dirnodes.
2147
2148         I return a Monitor, with results that are an IDeepCheckResults
2149         object.
2150
2151         TODO: If any of the directories I traverse are unrecoverable, the
2152         Monitor will report failure. If any of the files I check upon are
2153         unrecoverable, those problems will be reported in the
2154         IDeepCheckResults as usual, and the Monitor will not report a
2155         failure.
2156         """
2157
2158     def start_deep_check_and_repair(verify=False, add_lease=False):
2159         """Check upon the health of me and everything I can reach. Repair
2160         anything that isn't healthy.
2161
2162         This is a recursive form of check_and_repair(), useable only on
2163         dirnodes.
2164
2165         I return a Monitor, with results that are an
2166         IDeepCheckAndRepairResults object.
2167
2168         TODO: If any of the directories I traverse are unrecoverable, the
2169         Monitor will report failure. If any of the files I check upon are
2170         unrecoverable, those problems will be reported in the
2171         IDeepCheckResults as usual, and the Monitor will not report a
2172         failure.
2173         """
2174
2175
2176 class ICheckResults(Interface):
2177     """I contain the detailed results of a check/verify operation.
2178     """
2179
2180     def get_storage_index():
2181         """Return a string with the (binary) storage index."""
2182
2183     def get_storage_index_string():
2184         """Return a string with the (printable) abbreviated storage index."""
2185
2186     def get_uri():
2187         """Return the (string) URI of the object that was checked."""
2188
2189     def is_healthy():
2190         """Return a boolean, True if the file/dir is fully healthy, False if
2191         it is damaged in any way. Non-distributed LIT files always return
2192         True."""
2193
2194     def is_recoverable():
2195         """Return a boolean, True if the file/dir can be recovered, False if
2196         not. Unrecoverable files are obviously unhealthy. Non-distributed LIT
2197         files always return True."""
2198
2199     def needs_rebalancing():
2200         """Return a boolean, True if the file/dirs reliability could be
2201         improved by moving shares to new servers. Non-distributed LIT files
2202         always return False."""
2203
2204     # the following methods all return None for non-distributed LIT files
2205
2206     def get_encoding_needed():
2207         """Return 'k', the number of shares required for recovery"""
2208
2209     def get_encoding_expected():
2210         """Return 'N', the number of total shares generated"""
2211
2212     def get_share_counter_good():
2213         """Return the number of distinct good shares that were found. For
2214         mutable files, this counts shares for the 'best' version."""
2215
2216     def get_share_counter_wrong():
2217         """For mutable files, return the number of shares for versions other
2218         than the 'best' one (which is defined as being the recoverable
2219         version with the highest sequence number, then the highest roothash).
2220         These are either leftover shares from an older version (perhaps on a
2221         server that was offline when an update occurred), shares from an
2222         unrecoverable newer version, or shares from an alternate current
2223         version that results from an uncoordinated write collision. For a
2224         healthy file, this will equal 0. For immutable files, this will
2225         always equal 0."""
2226
2227     def get_corrupt_shares():
2228         """Return a list of 'share locators', one for each share that was
2229         found to be corrupt (integrity failure). Each share locator is a list
2230         of (IServer, storage_index, sharenum)."""
2231
2232     def get_incompatible_shares():
2233         """Return a list of 'share locators', one for each share that was
2234         found to be of an unknown format. Each share locator is a list of
2235         (IServer, storage_index, sharenum)."""
2236
2237     def get_servers_responding():
2238         """Return a list of IServer objects, one for each server which
2239         responded to the share query (even if they said they didn't have
2240         shares, and even if they said they did have shares but then didn't
2241         send them when asked, or dropped the connection, or returned a
2242         Failure, and even if they said they did have shares and sent
2243         incorrect ones when asked)"""
2244
2245     def get_host_counter_good_shares():
2246         """Return the number of distinct storage servers with good shares. If
2247         this number is less than get_share_counters()[good], then some shares
2248         are doubled up, increasing the correlation of failures. This
2249         indicates that one or more shares should be moved to an otherwise
2250         unused server, if one is available.
2251         """
2252
2253     def get_version_counter_recoverable():
2254         """Return the number of recoverable versions of the file. For a
2255         healthy file, this will equal 1."""
2256
2257     def get_version_counter_unrecoverable():
2258          """Return the number of unrecoverable versions of the file. For a
2259          healthy file, this will be 0."""
2260
2261     def get_sharemap():
2262         """Return a dict mapping share identifier to list of IServer objects.
2263         This indicates which servers are holding which shares. For immutable
2264         files, the shareid is an integer (the share number, from 0 to N-1).
2265         For mutable files, it is a string of the form 'seq%d-%s-sh%d',
2266         containing the sequence number, the roothash, and the share number."""
2267
2268     def get_summary():
2269         """Return a string with a brief (one-line) summary of the results."""
2270
2271     def get_report():
2272         """Return a list of strings with more detailed results."""
2273
2274
2275 class ICheckAndRepairResults(Interface):
2276     """I contain the detailed results of a check/verify/repair operation.
2277
2278     The IFilesystemNode.check()/verify()/repair() methods all return
2279     instances that provide ICheckAndRepairResults.
2280     """
2281
2282     def get_storage_index():
2283         """Return a string with the (binary) storage index."""
2284
2285     def get_storage_index_string():
2286         """Return a string with the (printable) abbreviated storage index."""
2287
2288     def get_repair_attempted():
2289         """Return a boolean, True if a repair was attempted. We might not
2290         attempt to repair the file because it was healthy, or healthy enough
2291         (i.e. some shares were missing but not enough to exceed some
2292         threshold), or because we don't know how to repair this object."""
2293
2294     def get_repair_successful():
2295         """Return a boolean, True if repair was attempted and the file/dir
2296         was fully healthy afterwards. False if no repair was attempted or if
2297         a repair attempt failed."""
2298
2299     def get_pre_repair_results():
2300         """Return an ICheckResults instance that describes the state of the
2301         file/dir before any repair was attempted."""
2302
2303     def get_post_repair_results():
2304         """Return an ICheckResults instance that describes the state of the
2305         file/dir after any repair was attempted. If no repair was attempted,
2306         the pre-repair and post-repair results will be identical."""
2307
2308
2309 class IDeepCheckResults(Interface):
2310     """I contain the results of a deep-check operation.
2311
2312     This is returned by a call to ICheckable.deep_check().
2313     """
2314
2315     def get_root_storage_index_string():
2316         """Return the storage index (abbreviated human-readable string) of
2317         the first object checked."""
2318
2319     def get_counters():
2320         """Return a dictionary with the following keys::
2321
2322              count-objects-checked: count of how many objects were checked
2323              count-objects-healthy: how many of those objects were completely
2324                                     healthy
2325              count-objects-unhealthy: how many were damaged in some way
2326              count-objects-unrecoverable: how many were unrecoverable
2327              count-corrupt-shares: how many shares were found to have
2328                                    corruption, summed over all objects
2329                                    examined
2330         """
2331
2332     def get_corrupt_shares():
2333         """Return a set of (IServer, storage_index, sharenum) for all shares
2334         that were found to be corrupt. storage_index is binary."""
2335
2336     def get_all_results():
2337         """Return a dictionary mapping pathname (a tuple of strings, ready to
2338         be slash-joined) to an ICheckResults instance, one for each object
2339         that was checked."""
2340
2341     def get_results_for_storage_index(storage_index):
2342         """Retrive the ICheckResults instance for the given (binary)
2343         storage index. Raises KeyError if there are no results for that
2344         storage index."""
2345
2346     def get_stats():
2347         """Return a dictionary with the same keys as
2348         IDirectoryNode.deep_stats()."""
2349
2350
2351 class IDeepCheckAndRepairResults(Interface):
2352     """I contain the results of a deep-check-and-repair operation.
2353
2354     This is returned by a call to ICheckable.deep_check_and_repair().
2355     """
2356
2357     def get_root_storage_index_string():
2358         """Return the storage index (abbreviated human-readable string) of
2359         the first object checked."""
2360
2361     def get_counters():
2362         """Return a dictionary with the following keys::
2363
2364              count-objects-checked: count of how many objects were checked
2365              count-objects-healthy-pre-repair: how many of those objects were
2366                                                completely healthy (before any
2367                                                repair)
2368              count-objects-unhealthy-pre-repair: how many were damaged in
2369                                                  some way
2370              count-objects-unrecoverable-pre-repair: how many were unrecoverable
2371              count-objects-healthy-post-repair: how many of those objects were
2372                                                 completely healthy (after any
2373                                                 repair)
2374              count-objects-unhealthy-post-repair: how many were damaged in
2375                                                   some way
2376              count-objects-unrecoverable-post-repair: how many were
2377                                                       unrecoverable
2378              count-repairs-attempted: repairs were attempted on this many
2379                                       objects. The count-repairs- keys will
2380                                       always be provided, however unless
2381                                       repair=true is present, they will all
2382                                       be zero.
2383              count-repairs-successful: how many repairs resulted in healthy
2384                                        objects
2385              count-repairs-unsuccessful: how many repairs resulted did not
2386                                          results in completely healthy objects
2387              count-corrupt-shares-pre-repair: how many shares were found to
2388                                               have corruption, summed over all
2389                                               objects examined (before any
2390                                               repair)
2391              count-corrupt-shares-post-repair: how many shares were found to
2392                                                have corruption, summed over all
2393                                                objects examined (after any
2394                                                repair)
2395         """
2396
2397     def get_stats():
2398         """Return a dictionary with the same keys as
2399         IDirectoryNode.deep_stats()."""
2400
2401     def get_corrupt_shares():
2402         """Return a set of (IServer, storage_index, sharenum) for all shares
2403         that were found to be corrupt before any repair was attempted.
2404         storage_index is binary.
2405         """
2406     def get_remaining_corrupt_shares():
2407         """Return a set of (IServer, storage_index, sharenum) for all shares
2408         that were found to be corrupt after any repair was completed.
2409         storage_index is binary. These are shares that need manual inspection
2410         and probably deletion.
2411         """
2412     def get_all_results():
2413         """Return a dictionary mapping pathname (a tuple of strings, ready to
2414         be slash-joined) to an ICheckAndRepairResults instance, one for each
2415         object that was checked."""
2416
2417     def get_results_for_storage_index(storage_index):
2418         """Retrive the ICheckAndRepairResults instance for the given (binary)
2419         storage index. Raises KeyError if there are no results for that
2420         storage index."""
2421
2422
2423 class IRepairable(Interface):
2424     def repair(check_results):
2425         """Attempt to repair the given object. Returns a Deferred that fires
2426         with a IRepairResults object.
2427
2428         I must be called with an object that implements ICheckResults, as
2429         proof that you have actually discovered a problem with this file. I
2430         will use the data in the checker results to guide the repair process,
2431         such as which servers provided bad data and should therefore be
2432         avoided. The ICheckResults object is inside the
2433         ICheckAndRepairResults object, which is returned by the
2434         ICheckable.check() method::
2435
2436          d = filenode.check(repair=False)
2437          def _got_results(check_and_repair_results):
2438              check_results = check_and_repair_results.get_pre_repair_results()
2439              return filenode.repair(check_results)
2440          d.addCallback(_got_results)
2441          return d
2442         """
2443
2444
2445 class IRepairResults(Interface):
2446     """I contain the results of a repair operation."""
2447     def get_successful():
2448         """Returns a boolean: True if the repair made the file healthy, False
2449         if not. Repair failure generally indicates a file that has been
2450         damaged beyond repair."""
2451
2452
2453 class IClient(Interface):
2454     def upload(uploadable):
2455         """Upload some data into a CHK, get back the UploadResults for it.
2456         @param uploadable: something that implements IUploadable
2457         @return: a Deferred that fires with the UploadResults instance.
2458                  To get the URI for this file, use results.uri .
2459         """
2460
2461     def create_mutable_file(contents=""):
2462         """Create a new mutable file (with initial) contents, get back the
2463         new node instance.
2464
2465         @param contents: (bytestring, callable, or None): this provides the
2466         initial contents of the mutable file. If 'contents' is a bytestring,
2467         it will be used as-is. If 'contents' is a callable, it will be
2468         invoked with the new MutableFileNode instance and is expected to
2469         return a bytestring with the initial contents of the file (the
2470         callable can use node.get_writekey() to decide how to encrypt the
2471         initial contents, e.g. for a brand new dirnode with initial
2472         children). contents=None is equivalent to an empty string. Using
2473         content_maker= is more efficient than creating a mutable file and
2474         setting its contents in two separate operations.
2475
2476         @return: a Deferred that fires with an IMutableFileNode instance.
2477         """
2478
2479     def create_dirnode(initial_children={}):
2480         """Create a new unattached dirnode, possibly with initial children.
2481
2482         @param initial_children: dict with keys that are unicode child names,
2483         and values that are (childnode, metadata) tuples.
2484
2485         @return: a Deferred that fires with the new IDirectoryNode instance.
2486         """
2487
2488     def create_node_from_uri(uri, rouri):
2489         """Create a new IFilesystemNode instance from the uri, synchronously.
2490         @param uri: a string or IURI-providing instance, or None. This could
2491                     be for a LiteralFileNode, a CHK file node, a mutable file
2492                     node, or a directory node
2493         @param rouri: a string or IURI-providing instance, or None. If the
2494                       main uri is None, I will use the rouri instead. If I
2495                       recognize the format of the main uri, I will ignore the
2496                       rouri (because it can be derived from the writecap).
2497
2498         @return: an instance that provides IFilesystemNode (or more usefully
2499                  one of its subclasses). File-specifying URIs will result in
2500                  IFileNode-providing instances, like ImmutableFileNode,
2501                  LiteralFileNode, or MutableFileNode. Directory-specifying
2502                  URIs will result in IDirectoryNode-providing instances, like
2503                  DirectoryNode.
2504         """
2505
2506
2507 class INodeMaker(Interface):
2508     """The NodeMaker is used to create IFilesystemNode instances. It can
2509     accept a filecap/dircap string and return the node right away. It can
2510     also create new nodes (i.e. upload a file, or create a mutable file)
2511     asynchronously. Once you have one of these nodes, you can use other
2512     methods to determine whether it is a file or directory, and to download
2513     or modify its contents.
2514
2515     The NodeMaker encapsulates all the authorities that these
2516     IFilesystemNodes require (like references to the StorageFarmBroker). Each
2517     Tahoe process will typically have a single NodeMaker, but unit tests may
2518     create simplified/mocked forms for testing purposes.
2519     """
2520     def create_from_cap(writecap, readcap=None, **kwargs):
2521         """I create an IFilesystemNode from the given writecap/readcap. I can
2522         only provide nodes for existing file/directory objects: use my other
2523         methods to create new objects. I return synchronously."""
2524
2525     def create_mutable_file(contents=None, keysize=None):
2526         """I create a new mutable file, and return a Deferred which will fire
2527         with the IMutableFileNode instance when it is ready. If contents= is
2528         provided (a bytestring), it will be used as the initial contents of
2529         the new file, otherwise the file will contain zero bytes. keysize= is
2530         for use by unit tests, to create mutable files that are smaller than
2531         usual."""
2532
2533     def create_new_mutable_directory(initial_children={}):
2534         """I create a new mutable directory, and return a Deferred which will
2535         fire with the IDirectoryNode instance when it is ready. If
2536         initial_children= is provided (a dict mapping unicode child name to
2537         (childnode, metadata_dict) tuples), the directory will be populated
2538         with those children, otherwise it will be empty."""
2539
2540
2541 class IClientStatus(Interface):
2542     def list_all_uploads():
2543         """Return a list of uploader objects, one for each upload which
2544         currently has an object available (tracked with weakrefs). This is
2545         intended for debugging purposes."""
2546
2547     def list_active_uploads():
2548         """Return a list of active IUploadStatus objects."""
2549
2550     def list_recent_uploads():
2551         """Return a list of IUploadStatus objects for the most recently
2552         started uploads."""
2553
2554     def list_all_downloads():
2555         """Return a list of downloader objects, one for each download which
2556         currently has an object available (tracked with weakrefs). This is
2557         intended for debugging purposes."""
2558
2559     def list_active_downloads():
2560         """Return a list of active IDownloadStatus objects."""
2561
2562     def list_recent_downloads():
2563         """Return a list of IDownloadStatus objects for the most recently
2564         started downloads."""
2565
2566
2567 class IUploadStatus(Interface):
2568     def get_started():
2569         """Return a timestamp (float with seconds since epoch) indicating
2570         when the operation was started."""
2571
2572     def get_storage_index():
2573         """Return a string with the (binary) storage index in use on this
2574         upload. Returns None if the storage index has not yet been
2575         calculated."""
2576
2577     def get_size():
2578         """Return an integer with the number of bytes that will eventually
2579         be uploaded for this file. Returns None if the size is not yet known.
2580         """
2581     def using_helper():
2582         """Return True if this upload is using a Helper, False if not."""
2583
2584     def get_status():
2585         """Return a string describing the current state of the upload
2586         process."""
2587
2588     def get_progress():
2589         """Returns a tuple of floats, (chk, ciphertext, encode_and_push),
2590         each from 0.0 to 1.0 . 'chk' describes how much progress has been
2591         made towards hashing the file to determine a CHK encryption key: if
2592         non-convergent encryption is in use, this will be trivial, otherwise
2593         the whole file must be hashed. 'ciphertext' describes how much of the
2594         ciphertext has been pushed to the helper, and is '1.0' for non-helper
2595         uploads. 'encode_and_push' describes how much of the encode-and-push
2596         process has finished: for helper uploads this is dependent upon the
2597         helper providing progress reports. It might be reasonable to add all
2598         three numbers and report the sum to the user."""
2599
2600     def get_active():
2601         """Return True if the upload is currently active, False if not."""
2602
2603     def get_results():
2604         """Return an instance of UploadResults (which contains timing and
2605         sharemap information). Might return None if the upload is not yet
2606         finished."""
2607
2608     def get_counter():
2609         """Each upload status gets a unique number: this method returns that
2610         number. This provides a handle to this particular upload, so a web
2611         page can generate a suitable hyperlink."""
2612
2613
2614 class IDownloadStatus(Interface):
2615     def get_started():
2616         """Return a timestamp (float with seconds since epoch) indicating
2617         when the operation was started."""
2618
2619     def get_storage_index():
2620         """Return a string with the (binary) storage index in use on this
2621         download. This may be None if there is no storage index (i.e. LIT
2622         files)."""
2623
2624     def get_size():
2625         """Return an integer with the number of bytes that will eventually be
2626         retrieved for this file. Returns None if the size is not yet known.
2627         """
2628
2629     def using_helper():
2630         """Return True if this download is using a Helper, False if not."""
2631
2632     def get_status():
2633         """Return a string describing the current state of the download
2634         process."""
2635
2636     def get_progress():
2637         """Returns a float (from 0.0 to 1.0) describing the amount of the
2638         download that has completed. This value will remain at 0.0 until the
2639         first byte of plaintext is pushed to the download target."""
2640
2641     def get_active():
2642         """Return True if the download is currently active, False if not."""
2643
2644     def get_counter():
2645         """Each download status gets a unique number: this method returns
2646         that number. This provides a handle to this particular download, so a
2647         web page can generate a suitable hyperlink."""
2648
2649
2650 class IServermapUpdaterStatus(Interface):
2651     pass
2652
2653 class IPublishStatus(Interface):
2654     pass
2655
2656 class IRetrieveStatus(Interface):
2657     pass
2658
2659
2660 class NotCapableError(Exception):
2661     """You have tried to write to a read-only node."""
2662
2663 class BadWriteEnablerError(Exception):
2664     pass
2665
2666 class RIControlClient(RemoteInterface):
2667
2668     def wait_for_client_connections(num_clients=int):
2669         """Do not return until we have connections to at least NUM_CLIENTS
2670         storage servers.
2671         """
2672
2673     def upload_from_file_to_uri(filename=str,
2674                                 convergence=ChoiceOf(None,
2675                                                      StringConstraint(2**20))):
2676         """Upload a file to the grid. This accepts a filename (which must be
2677         absolute) that points to a file on the node's local disk. The node will
2678         read the contents of this file, upload it to the grid, then return the
2679         URI at which it was uploaded.  If convergence is None then a random
2680         encryption key will be used, else the plaintext will be hashed, then
2681         that hash will be mixed together with the "convergence" string to form
2682         the encryption key.
2683         """
2684         return URI
2685
2686     def download_from_uri_to_file(uri=URI, filename=str):
2687         """Download a file from the grid, placing it on the node's local disk
2688         at the given filename (which must be absolute[?]). Returns the
2689         absolute filename where the file was written."""
2690         return str
2691
2692     # debug stuff
2693
2694     def get_memory_usage():
2695         """Return a dict describes the amount of memory currently in use. The
2696         keys are 'VmPeak', 'VmSize', and 'VmData'. The values are integers,
2697         measuring memory consupmtion in bytes."""
2698         return DictOf(str, int)
2699
2700     def speed_test(count=int, size=int, mutable=Any()):
2701         """Write 'count' tempfiles to disk, all of the given size. Measure
2702         how long (in seconds) it takes to upload them all to the servers.
2703         Then measure how long it takes to download all of them. If 'mutable'
2704         is 'create', time creation of mutable files. If 'mutable' is
2705         'upload', then time access to the same mutable file instead of
2706         creating one.
2707
2708         Returns a tuple of (upload_time, download_time).
2709         """
2710         return (float, float)
2711
2712     def measure_peer_response_time():
2713         """Send a short message to each connected peer, and measure the time
2714         it takes for them to respond to it. This is a rough measure of the
2715         application-level round trip time.
2716
2717         @return: a dictionary mapping peerid to a float (RTT time in seconds)
2718         """
2719
2720         return DictOf(str, float)
2721
2722
2723 UploadResults = Any() #DictOf(str, str)
2724
2725
2726 class RIEncryptedUploadable(RemoteInterface):
2727     __remote_name__ = "RIEncryptedUploadable.tahoe.allmydata.com"
2728
2729     def get_size():
2730         return Offset
2731
2732     def get_all_encoding_parameters():
2733         return (int, int, int, long)
2734
2735     def read_encrypted(offset=Offset, length=ReadSize):
2736         return ListOf(str)
2737
2738     def close():
2739         return None
2740
2741
2742 class RICHKUploadHelper(RemoteInterface):
2743     __remote_name__ = "RIUploadHelper.tahoe.allmydata.com"
2744
2745     def get_version():
2746         """
2747         Return a dictionary of version information.
2748         """
2749         return DictOf(str, Any())
2750
2751     def upload(reader=RIEncryptedUploadable):
2752         return UploadResults
2753
2754
2755 class RIHelper(RemoteInterface):
2756     __remote_name__ = "RIHelper.tahoe.allmydata.com"
2757
2758     def get_version():
2759         """
2760         Return a dictionary of version information.
2761         """
2762         return DictOf(str, Any())
2763
2764     def upload_chk(si=StorageIndex):
2765         """See if a file with a given storage index needs uploading. The
2766         helper will ask the appropriate storage servers to see if the file
2767         has already been uploaded. If so, the helper will return a set of
2768         'upload results' that includes whatever hashes are needed to build
2769         the read-cap, and perhaps a truncated sharemap.
2770
2771         If the file has not yet been uploaded (or if it was only partially
2772         uploaded), the helper will return an empty upload-results dictionary
2773         and also an RICHKUploadHelper object that will take care of the
2774         upload process. The client should call upload() on this object and
2775         pass it a reference to an RIEncryptedUploadable object that will
2776         provide ciphertext. When the upload is finished, the upload() method
2777         will finish and return the upload results.
2778         """
2779         return (UploadResults, ChoiceOf(RICHKUploadHelper, None))
2780
2781
2782 class RIStatsProvider(RemoteInterface):
2783     __remote_name__ = "RIStatsProvider.tahoe.allmydata.com"
2784     """
2785     Provides access to statistics and monitoring information.
2786     """
2787
2788     def get_stats():
2789         """
2790         returns a dictionary containing 'counters' and 'stats', each a
2791         dictionary with string counter/stat name keys, and numeric or None values.
2792         counters are monotonically increasing measures of work done, and
2793         stats are instantaneous measures (potentially time averaged
2794         internally)
2795         """
2796         return DictOf(str, DictOf(str, ChoiceOf(float, int, long, None)))
2797
2798
2799 class RIStatsGatherer(RemoteInterface):
2800     __remote_name__ = "RIStatsGatherer.tahoe.allmydata.com"
2801     """
2802     Provides a monitoring service for centralised collection of stats
2803     """
2804
2805     def provide(provider=RIStatsProvider, nickname=str):
2806         """
2807         @param provider: a stats collector instance which should be polled
2808                          periodically by the gatherer to collect stats.
2809         @param nickname: a name useful to identify the provided client
2810         """
2811         return None
2812
2813
2814 class IStatsProducer(Interface):
2815     def get_stats():
2816         """
2817         returns a dictionary, with str keys representing the names of stats
2818         to be monitored, and numeric values.
2819         """
2820
2821 class RIKeyGenerator(RemoteInterface):
2822     __remote_name__ = "RIKeyGenerator.tahoe.allmydata.com"
2823     """
2824     Provides a service offering to make RSA key pairs.
2825     """
2826
2827     def get_rsa_key_pair(key_size=int):
2828         """
2829         @param key_size: the size of the signature key.
2830         @return: tuple(verifying_key, signing_key)
2831         """
2832         return TupleOf(str, str)
2833
2834
2835 class FileTooLargeError(Exception):
2836     pass
2837
2838
2839 class IValidatedThingProxy(Interface):
2840     def start():
2841         """ Acquire a thing and validate it. Return a deferred which is
2842         eventually fired with self if the thing is valid or errbacked if it
2843         can't be acquired or validated."""
2844
2845
2846 class InsufficientVersionError(Exception):
2847     def __init__(self, needed, got):
2848         self.needed = needed
2849         self.got = got
2850
2851     def __repr__(self):
2852         return "InsufficientVersionError(need '%s', got %s)" % (self.needed,
2853                                                                 self.got)
2854
2855 class EmptyPathnameComponentError(Exception):
2856     """The webapi disallows empty pathname components."""