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