]> git.rkrishnan.org Git - tahoe-lafs/tahoe-lafs.git/blob - src/allmydata/interfaces.py
manifest: include stats in results. webapi is unchanged.
[tahoe-lafs/tahoe-lafs.git] / src / allmydata / interfaces.py
1
2 from zope.interface import Interface
3 from foolscap.schema import StringConstraint, ListOf, TupleOf, SetOf, DictOf, \
4      ChoiceOf, IntegerConstraint
5 from foolscap import RemoteInterface, Referenceable
6
7 HASH_SIZE=32
8
9 Hash = StringConstraint(maxLength=HASH_SIZE,
10                         minLength=HASH_SIZE)# binary format 32-byte SHA256 hash
11 Nodeid = StringConstraint(maxLength=20,
12                           minLength=20) # binary format 20-byte SHA1 hash
13 FURL = StringConstraint(1000)
14 StorageIndex = StringConstraint(16)
15 URI = StringConstraint(300) # kind of arbitrary
16
17 MAX_BUCKETS = 256  # per peer -- zfec offers at most 256 shares per file
18
19 ShareData = StringConstraint(None)
20 URIExtensionData = StringConstraint(1000)
21 Number = IntegerConstraint(8) # 2**(8*8) == 16EiB ~= 18e18 ~= 18 exabytes
22 Offset = Number
23 ReadSize = int # the 'int' constraint is 2**31 == 2Gib -- large files are processed in not-so-large increments
24 WriteEnablerSecret = Hash # used to protect mutable bucket modifications
25 LeaseRenewSecret = Hash # used to protect bucket lease renewal requests
26 LeaseCancelSecret = Hash # used to protect bucket lease cancellation requests
27
28 class RIStubClient(RemoteInterface):
29     """Each client publishes a service announcement for a dummy object called
30     the StubClient. This object doesn't actually offer any services, but the
31     announcement helps the Introducer keep track of which clients are
32     subscribed (so the grid admin can keep track of things like the size of
33     the grid and the client versions in use. This is the (empty)
34     RemoteInterface for the StubClient."""
35
36 class RIBucketWriter(RemoteInterface):
37     """ Objects of this kind live on the server side. """
38     def write(offset=Offset, data=ShareData):
39         return None
40
41     def close():
42         """
43         If the data that has been written is incomplete or inconsistent then
44         the server will throw the data away, else it will store it for future
45         retrieval.
46         """
47         return None
48
49     def abort():
50         """Abandon all the data that has been written.
51         """
52         return None
53
54 class RIBucketReader(RemoteInterface):
55     def read(offset=Offset, length=ReadSize):
56         return ShareData
57
58     def advise_corrupt_share(reason=str):
59         """Clients who discover hash failures in shares that they have
60         downloaded from me will use this method to inform me about the
61         failures. I will record their concern so that my operator can
62         manually inspect the shares in question. I return None.
63
64         This is a wrapper around RIStorageServer.advise_corrupt_share(),
65         which is tied to a specific share, and therefore does not need the
66         extra share-identifying arguments. Please see that method for full
67         documentation.
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 class RIStorageServer(RemoteInterface):
87     __remote_name__ = "RIStorageServer.tahoe.allmydata.com"
88
89     def get_versions():
90         """
91         Return a tuple of (my_version, oldest_supported) strings.  Each string can be parsed by
92         a pyutil.version_class.Version instance or a distutils.version.LooseVersion instance,
93         and then compared. The first goal is to make sure that nodes are not confused by
94         speaking to an incompatible peer. The second goal is to enable the development of
95         backwards-compatibility code.
96
97         The meaning of the oldest_supported element is that if you treat this storage server as
98         though it were of that version, then you will not be disappointed.
99
100         The precise meaning of this method might change in incompatible ways until we get the
101         whole compatibility scheme nailed down.
102         """
103         return TupleOf(str, str)
104
105     def allocate_buckets(storage_index=StorageIndex,
106                          renew_secret=LeaseRenewSecret,
107                          cancel_secret=LeaseCancelSecret,
108                          sharenums=SetOf(int, maxLength=MAX_BUCKETS),
109                          allocated_size=Offset, canary=Referenceable):
110         """
111         @param storage_index: the index of the bucket to be created or
112                               increfed.
113         @param sharenums: these are the share numbers (probably between 0 and
114                           99) that the sender is proposing to store on this
115                           server.
116         @param renew_secret: This is the secret used to protect bucket refresh
117                              This secret is generated by the client and
118                              stored for later comparison by the server. Each
119                              server is given a different secret.
120         @param cancel_secret: Like renew_secret, but protects bucket decref.
121         @param canary: If the canary is lost before close(), the bucket is
122                        deleted.
123         @return: tuple of (alreadygot, allocated), where alreadygot is what we
124                  already have and is what we hereby agree to accept. New
125                  leases are added for shares in both lists.
126         """
127         return TupleOf(SetOf(int, maxLength=MAX_BUCKETS),
128                        DictOf(int, RIBucketWriter, maxKeys=MAX_BUCKETS))
129
130     def add_lease(storage_index=StorageIndex,
131                   renew_secret=LeaseRenewSecret,
132                   cancel_secret=LeaseCancelSecret):
133         """
134         Add a new lease on the given bucket. If the renew_secret matches an
135         existing lease, that lease will be renewed instead.
136         """
137         return None
138
139     def renew_lease(storage_index=StorageIndex, renew_secret=LeaseRenewSecret):
140         """
141         Renew the lease on a given bucket. Some networks will use this, some
142         will not.
143         """
144         return None
145
146     def cancel_lease(storage_index=StorageIndex,
147                      cancel_secret=LeaseCancelSecret):
148         """
149         Cancel the lease on a given bucket. If this was the last lease on the
150         bucket, the bucket will be deleted.
151         """
152         return None
153
154     def get_buckets(storage_index=StorageIndex):
155         return DictOf(int, RIBucketReader, maxKeys=MAX_BUCKETS)
156
157
158
159     def slot_readv(storage_index=StorageIndex,
160                    shares=ListOf(int), readv=ReadVector):
161         """Read a vector from the numbered shares associated with the given
162         storage index. An empty shares list means to return data from all
163         known shares. Returns a dictionary with one key per share."""
164         return DictOf(int, ReadData) # shnum -> results
165
166     def slot_testv_and_readv_and_writev(storage_index=StorageIndex,
167                                         secrets=TupleOf(WriteEnablerSecret,
168                                                         LeaseRenewSecret,
169                                                         LeaseCancelSecret),
170                                         tw_vectors=TestAndWriteVectorsForShares,
171                                         r_vector=ReadVector,
172                                         ):
173         """General-purpose test-and-set operation for mutable slots. Perform
174         a bunch of comparisons against the existing shares. If they all pass,
175         then apply a bunch of write vectors to those shares. Then use the
176         read vectors to extract data from all the shares and return the data.
177
178         This method is, um, large. The goal is to allow clients to update all
179         the shares associated with a mutable file in a single round trip.
180
181         @param storage_index: the index of the bucket to be created or
182                               increfed.
183         @param write_enabler: a secret that is stored along with the slot.
184                               Writes are accepted from any caller who can
185                               present the matching secret. A different secret
186                               should be used for each slot*server pair.
187         @param renew_secret: This is the secret used to protect bucket refresh
188                              This secret is generated by the client and
189                              stored for later comparison by the server. Each
190                              server is given a different secret.
191         @param cancel_secret: Like renew_secret, but protects bucket decref.
192
193         The 'secrets' argument is a tuple of (write_enabler, renew_secret,
194         cancel_secret). The first is required to perform any write. The
195         latter two are used when allocating new shares. To simply acquire a
196         new lease on existing shares, use an empty testv and an empty writev.
197
198         Each share can have a separate test vector (i.e. a list of
199         comparisons to perform). If all vectors for all shares pass, then all
200         writes for all shares are recorded. Each comparison is a 4-tuple of
201         (offset, length, operator, specimen), which effectively does a bool(
202         (read(offset, length)) OPERATOR specimen ) and only performs the
203         write if all these evaluate to True. Basic test-and-set uses 'eq'.
204         Write-if-newer uses a seqnum and (offset, length, 'lt', specimen).
205         Write-if-same-or-newer uses 'le'.
206
207         Reads from the end of the container are truncated, and missing shares
208         behave like empty ones, so to assert that a share doesn't exist (for
209         use when creating a new share), use (0, 1, 'eq', '').
210
211         The write vector will be applied to the given share, expanding it if
212         necessary. A write vector applied to a share number that did not
213         exist previously will cause that share to be created.
214
215         Each write vector is accompanied by a 'new_length' argument. If
216         new_length is not None, use it to set the size of the container. This
217         can be used to pre-allocate space for a series of upcoming writes, or
218         truncate existing data. If the container is growing, new_length will
219         be applied before datav. If the container is shrinking, it will be
220         applied afterwards.
221
222         The read vector is used to extract data from all known shares,
223         *before* any writes have been applied. The same vector is used for
224         all shares. This captures the state that was tested by the test
225         vector.
226
227         This method returns two values: a boolean and a dict. The boolean is
228         True if the write vectors were applied, False if not. The dict is
229         keyed by share number, and each value contains a list of strings, one
230         for each element of the read vector.
231
232         If the write_enabler is wrong, this will raise BadWriteEnablerError.
233         To enable share migration (using update_write_enabler), the exception
234         will have the nodeid used for the old write enabler embedded in it,
235         in the following string::
236
237          The write enabler was recorded by nodeid '%s'.
238
239         Note that the nodeid here is encoded using the same base32 encoding
240         used by Foolscap and allmydata.util.idlib.nodeid_b2a().
241
242         """
243         return TupleOf(bool, DictOf(int, ReadData))
244
245     def advise_corrupt_share(share_type=str, storage_index=StorageIndex,
246                              shnum=int, reason=str):
247         """Clients who discover hash failures in shares that they have
248         downloaded from me will use this method to inform me about the
249         failures. I will record their concern so that my operator can
250         manually inspect the shares in question. I return None.
251
252         'share_type' is either 'mutable' or 'immutable'. 'storage_index' is a
253         (binary) storage index string, and 'shnum' is the integer share
254         number. 'reason' is a human-readable explanation of the problem,
255         probably including some expected hash values and the computed ones
256         which did not match. Corruption advisories for mutable shares should
257         include a hash of the public key (the same value that appears in the
258         mutable-file verify-cap), since the current share format does not
259         store that on disk.
260         """
261
262 class IStorageBucketWriter(Interface):
263     """
264     Objects of this kind live on the client side.
265     """
266     def put_block(segmentnum=int, data=ShareData):
267         """@param data: For most segments, this data will be 'blocksize'
268         bytes in length. The last segment might be shorter.
269         @return: a Deferred that fires (with None) when the operation completes
270         """
271
272     def put_plaintext_hashes(hashes=ListOf(Hash)):
273         """
274         @return: a Deferred that fires (with None) when the operation completes
275         """
276
277     def put_crypttext_hashes(hashes=ListOf(Hash)):
278         """
279         @return: a Deferred that fires (with None) when the operation completes
280         """
281
282     def put_block_hashes(blockhashes=ListOf(Hash)):
283         """
284         @return: a Deferred that fires (with None) when the operation completes
285         """
286
287     def put_share_hashes(sharehashes=ListOf(TupleOf(int, Hash))):
288         """
289         @return: a Deferred that fires (with None) when the operation completes
290         """
291
292     def put_uri_extension(data=URIExtensionData):
293         """This block of data contains integrity-checking information (hashes
294         of plaintext, crypttext, and shares), as well as encoding parameters
295         that are necessary to recover the data. This is a serialized dict
296         mapping strings to other strings. The hash of this data is kept in
297         the URI and verified before any of the data is used. All buckets for
298         a given file contain identical copies of this data.
299
300         The serialization format is specified with the following pseudocode:
301         for k in sorted(dict.keys()):
302             assert re.match(r'^[a-zA-Z_\-]+$', k)
303             write(k + ':' + netstring(dict[k]))
304
305         @return: a Deferred that fires (with None) when the operation completes
306         """
307
308     def close():
309         """Finish writing and close the bucket. The share is not finalized
310         until this method is called: if the uploading client disconnects
311         before calling close(), the partially-written share will be
312         discarded.
313
314         @return: a Deferred that fires (with None) when the operation completes
315         """
316
317 class IStorageBucketReader(Interface):
318
319     def get_block(blocknum=int):
320         """Most blocks will be the same size. The last block might be shorter
321         than the others.
322
323         @return: ShareData
324         """
325
326     def get_plaintext_hashes():
327         """
328         @return: ListOf(Hash)
329         """
330
331     def get_crypttext_hashes():
332         """
333         @return: ListOf(Hash)
334         """
335
336     def get_block_hashes():
337         """
338         @return: ListOf(Hash)
339         """
340
341     def get_share_hashes():
342         """
343         @return: ListOf(TupleOf(int, Hash))
344         """
345
346     def get_uri_extension():
347         """
348         @return: URIExtensionData
349         """
350
351
352
353 # hm, we need a solution for forward references in schemas
354 from foolscap.schema import Any
355
356 FileNode_ = Any() # TODO: foolscap needs constraints on copyables
357 DirectoryNode_ = Any() # TODO: same
358 AnyNode_ = ChoiceOf(FileNode_, DirectoryNode_)
359 EncryptedThing = str
360
361 class IURI(Interface):
362     def init_from_string(uri):
363         """Accept a string (as created by my to_string() method) and populate
364         this instance with its data. I am not normally called directly,
365         please use the module-level uri.from_string() function to convert
366         arbitrary URI strings into IURI-providing instances."""
367
368     def is_readonly():
369         """Return False if this URI be used to modify the data. Return True
370         if this URI cannot be used to modify the data."""
371
372     def is_mutable():
373         """Return True if the data can be modified by *somebody* (perhaps
374         someone who has a more powerful URI than this one)."""
375
376     def get_readonly():
377         """Return another IURI instance, which represents a read-only form of
378         this one. If is_readonly() is True, this returns self."""
379
380     def get_verifier():
381         """Return an instance that provides IVerifierURI, which can be used
382         to check on the availability of the file or directory, without
383         providing enough capabilities to actually read or modify the
384         contents. This may return None if the file does not need checking or
385         verification (e.g. LIT URIs).
386         """
387
388     def to_string():
389         """Return a string of printable ASCII characters, suitable for
390         passing into init_from_string."""
391
392 class IVerifierURI(Interface):
393     def init_from_string(uri):
394         """Accept a string (as created by my to_string() method) and populate
395         this instance with its data. I am not normally called directly,
396         please use the module-level uri.from_string() function to convert
397         arbitrary URI strings into IURI-providing instances."""
398
399     def to_string():
400         """Return a string of printable ASCII characters, suitable for
401         passing into init_from_string."""
402
403 class IDirnodeURI(Interface):
404     """I am a URI which represents a dirnode."""
405
406
407 class IFileURI(Interface):
408     """I am a URI which represents a filenode."""
409     def get_size():
410         """Return the length (in bytes) of the file that I represent."""
411
412 class IMutableFileURI(Interface):
413     """I am a URI which represents a mutable filenode."""
414 class INewDirectoryURI(Interface):
415     pass
416 class IReadonlyNewDirectoryURI(Interface):
417     pass
418
419
420 class IFilesystemNode(Interface):
421     def get_uri():
422         """
423         Return the URI that can be used by others to get access to this
424         node. If this node is read-only, the URI will only offer read-only
425         access. If this node is read-write, the URI will offer read-write
426         access.
427
428         If you have read-write access to a node and wish to share merely
429         read-only access with others, use get_readonly_uri().
430         """
431
432     def get_readonly_uri():
433         """Return the directory URI that can be used by others to get
434         read-only access to this directory node. The result is a read-only
435         URI, regardless of whether this dirnode is read-only or read-write.
436
437         If you have merely read-only access to this dirnode,
438         get_readonly_uri() will return the same thing as get_uri().
439         """
440
441     def get_verifier():
442         """Return an IVerifierURI instance that represents the
443         'verifiy/refresh capability' for this node. The holder of this
444         capability will be able to renew the lease for this node, protecting
445         it from garbage-collection. They will also be able to ask a server if
446         it holds a share for the file or directory.
447         """
448
449     def get_storage_index():
450         """Return a string with the (binary) storage index in use on this
451         download. This may be None if there is no storage index (i.e. LIT
452         files)."""
453
454     def is_readonly():
455         """Return True if this reference provides mutable access to the given
456         file or directory (i.e. if you can modify it), or False if not. Note
457         that even if this reference is read-only, someone else may hold a
458         read-write reference to it."""
459
460     def is_mutable():
461         """Return True if this file or directory is mutable (by *somebody*,
462         not necessarily you), False if it is is immutable. Note that a file
463         might be mutable overall, but your reference to it might be
464         read-only. On the other hand, all references to an immutable file
465         will be read-only; there are no read-write references to an immutable
466         file.
467         """
468
469 class IMutableFilesystemNode(IFilesystemNode):
470     pass
471
472 class IFileNode(IFilesystemNode):
473     def download(target):
474         """Download the file's contents to a given IDownloadTarget"""
475
476     def download_to_data():
477         """Download the file's contents. Return a Deferred that fires
478         with those contents."""
479
480     def get_size():
481         """Return the length (in bytes) of the data this node represents."""
482
483     def read(consumer, offset=0, size=None):
484         """Download a portion (possibly all) of the file's contents, making
485         them available to the given IConsumer. Return a Deferred that fires
486         (with the consumer) when the consumer is unregistered (either because
487         the last byte has been given to it, or because the consumer threw an
488         exception during write(), possibly because it no longer wants to
489         receive data). The portion downloaded will start at 'offset' and
490         contain 'size' bytes (or the remainder of the file if size==None).
491
492         The consumer will be used in non-streaming mode: an IPullProducer
493         will be attached to it.
494
495         The consumer will not receive data right away: several network trips
496         must occur first. The order of events will be::
497
498          consumer.registerProducer(p, streaming)
499           (if streaming == False)::
500            consumer does p.resumeProducing()
501             consumer.write(data)
502            consumer does p.resumeProducing()
503             consumer.write(data).. (repeat until all data is written)
504          consumer.unregisterProducer()
505          deferred.callback(consumer)
506
507         If a download error occurs, or an exception is raised by
508         consumer.registerProducer() or consumer.write(), I will call
509         consumer.unregisterProducer() and then deliver the exception via
510         deferred.errback(). To cancel the download, the consumer should call
511         p.stopProducing(), which will result in an exception being delivered
512         via deferred.errback().
513
514         A simple download-to-memory consumer example would look like this::
515
516          class MemoryConsumer:
517            implements(IConsumer)
518            def __init__(self):
519              self.chunks = []
520              self.done = False
521            def registerProducer(self, p, streaming):
522              assert streaming == False
523              while not self.done:
524                p.resumeProducing()
525            def write(self, data):
526              self.chunks.append(data)
527            def unregisterProducer(self):
528              self.done = True
529          d = filenode.read(MemoryConsumer())
530          d.addCallback(lambda mc: "".join(mc.chunks))
531          return d
532
533         """
534
535 class IMutableFileNode(IFileNode, IMutableFilesystemNode):
536     """I provide access to a 'mutable file', which retains its identity
537     regardless of what contents are put in it.
538
539     The consistency-vs-availability problem means that there might be
540     multiple versions of a file present in the grid, some of which might be
541     unrecoverable (i.e. have fewer than 'k' shares). These versions are
542     loosely ordered: each has a sequence number and a hash, and any version
543     with seqnum=N was uploaded by a node which has seen at least one version
544     with seqnum=N-1.
545
546     The 'servermap' (an instance of IMutableFileServerMap) is used to
547     describe the versions that are known to be present in the grid, and which
548     servers are hosting their shares. It is used to represent the 'state of
549     the world', and is used for this purpose by my test-and-set operations.
550     Downloading the contents of the mutable file will also return a
551     servermap. Uploading a new version into the mutable file requires a
552     servermap as input, and the semantics of the replace operation is
553     'replace the file with my new version if it looks like nobody else has
554     changed the file since my previous download'. Because the file is
555     distributed, this is not a perfect test-and-set operation, but it will do
556     its best. If the replace process sees evidence of a simultaneous write,
557     it will signal an UncoordinatedWriteError, so that the caller can take
558     corrective action.
559
560
561     Most readers will want to use the 'best' current version of the file, and
562     should use my 'download_best_version()' method.
563
564     To unconditionally replace the file, callers should use overwrite(). This
565     is the mode that user-visible mutable files will probably use.
566
567     To apply some delta to the file, call modify() with a callable modifier
568     function that can apply the modification that you want to make. This is
569     the mode that dirnodes will use, since most directory modification
570     operations can be expressed in terms of deltas to the directory state.
571
572
573     Three methods are available for users who need to perform more complex
574     operations. The first is get_servermap(), which returns an up-to-date
575     servermap using a specified mode. The second is download_version(), which
576     downloads a specific version (not necessarily the 'best' one). The third
577     is 'upload', which accepts new contents and a servermap (which must have
578     been updated with MODE_WRITE). The upload method will attempt to apply
579     the new contents as long as no other node has modified the file since the
580     servermap was updated. This might be useful to a caller who wants to
581     merge multiple versions into a single new one.
582
583     Note that each time the servermap is updated, a specific 'mode' is used,
584     which determines how many peers are queried. To use a servermap for my
585     replace() method, that servermap must have been updated in MODE_WRITE.
586     These modes are defined in allmydata.mutable.common, and consist of
587     MODE_READ, MODE_WRITE, MODE_ANYTHING, and MODE_CHECK. Please look in
588     allmydata/mutable/servermap.py for details about the differences.
589
590     Mutable files are currently limited in size (about 3.5MB max) and can
591     only be retrieved and updated all-at-once, as a single big string. Future
592     versions of our mutable files will remove this restriction.
593     """
594
595     def download_best_version():
596         """Download the 'best' available version of the file, meaning one of
597         the recoverable versions with the highest sequence number. If no
598         uncoordinated writes have occurred, and if enough shares are
599         available, then this will be the most recent version that has been
600         uploaded.
601
602         I update an internal servermap with MODE_READ, determine which
603         version of the file is indicated by
604         servermap.best_recoverable_version(), and return a Deferred that
605         fires with its contents. If no version is recoverable, the Deferred
606         will errback with UnrecoverableFileError.
607         """
608
609     def get_size_of_best_version():
610         """Find the size of the version that would be downloaded with
611         download_best_version(), without actually downloading the whole file.
612
613         I return a Deferred that fires with an integer.
614         """
615
616     def overwrite(new_contents):
617         """Unconditionally replace the contents of the mutable file with new
618         ones. This simply chains get_servermap(MODE_WRITE) and upload(). This
619         is only appropriate to use when the new contents of the file are
620         completely unrelated to the old ones, and you do not care about other
621         clients' changes.
622
623         I return a Deferred that fires (with a PublishStatus object) when the
624         update has completed.
625         """
626
627     def modify(modifier_cb):
628         """Modify the contents of the file, by downloading the current
629         version, applying the modifier function (or bound method), then
630         uploading the new version. I return a Deferred that fires (with a
631         PublishStatus object) when the update is complete.
632
633         The modifier callable will be given two arguments: a string (with the
634         old contents) and a servermap. As with download_best_version(), the
635         old contents will be from the best recoverable version, but the
636         modifier can use the servermap to make other decisions (such as
637         refusing to apply the delta if there are multiple parallel versions,
638         or if there is evidence of a newer unrecoverable version).
639
640         The callable should return a string with the new contents. The
641         callable must be prepared to be called multiple times, and must
642         examine the input string to see if the change that it wants to make
643         is already present in the old version. If it does not need to make
644         any changes, it can either return None, or return its input string.
645
646         If the modifier raises an exception, it will be returned in the
647         errback.
648         """
649
650
651     def get_servermap(mode):
652         """Return a Deferred that fires with an IMutableFileServerMap
653         instance, updated using the given mode.
654         """
655
656     def download_version(servermap, version):
657         """Download a specific version of the file, using the servermap
658         as a guide to where the shares are located.
659
660         I return a Deferred that fires with the requested contents, or
661         errbacks with UnrecoverableFileError. Note that a servermap which was
662         updated with MODE_ANYTHING or MODE_READ may not know about shares for
663         all versions (those modes stop querying servers as soon as they can
664         fulfil their goals), so you may want to use MODE_CHECK (which checks
665         everything) to get increased visibility.
666         """
667
668     def upload(new_contents, servermap):
669         """Replace the contents of the file with new ones. This requires a
670         servermap that was previously updated with MODE_WRITE.
671
672         I attempt to provide test-and-set semantics, in that I will avoid
673         modifying any share that is different than the version I saw in the
674         servermap. However, if another node is writing to the file at the
675         same time as me, I may manage to update some shares while they update
676         others. If I see any evidence of this, I will signal
677         UncoordinatedWriteError, and the file will be left in an inconsistent
678         state (possibly the version you provided, possibly the old version,
679         possibly somebody else's version, and possibly a mix of shares from
680         all of these).
681
682         The recommended response to UncoordinatedWriteError is to either
683         return it to the caller (since they failed to coordinate their
684         writes), or to attempt some sort of recovery. It may be sufficient to
685         wait a random interval (with exponential backoff) and repeat your
686         operation. If I do not signal UncoordinatedWriteError, then I was
687         able to write the new version without incident.
688
689         I return a Deferred that fires (with a PublishStatus object) when the
690         publish has completed. I will update the servermap in-place with the
691         location of all new shares.
692         """
693
694     def get_writekey():
695         """Return this filenode's writekey, or None if the node does not have
696         write-capability. This may be used to assist with data structures
697         that need to make certain data available only to writers, such as the
698         read-write child caps in dirnodes. The recommended process is to have
699         reader-visible data be submitted to the filenode in the clear (where
700         it will be encrypted by the filenode using the readkey), but encrypt
701         writer-visible data using this writekey.
702         """
703
704 class NotEnoughSharesError(Exception):
705     servermap = None
706
707 class ExistingChildError(Exception):
708     """A directory node was asked to add or replace a child that already
709     exists, and overwrite= was set to False."""
710
711 class NoSuchChildError(Exception):
712     """A directory node was asked to fetch a child which does not exist."""
713
714 class IDirectoryNode(IMutableFilesystemNode):
715     """I represent a name-to-child mapping, holding the tahoe equivalent of a
716     directory. All child names are unicode strings, and all children are some
717     sort of IFilesystemNode (either files or subdirectories).
718     """
719
720     def get_uri():
721         """
722         The dirnode ('1') URI returned by this method can be used in
723         set_uri() on a different directory ('2') to 'mount' a reference to
724         this directory ('1') under the other ('2'). This URI is just a
725         string, so it can be passed around through email or other out-of-band
726         protocol.
727         """
728
729     def get_readonly_uri():
730         """
731         The dirnode ('1') URI returned by this method can be used in
732         set_uri() on a different directory ('2') to 'mount' a reference to
733         this directory ('1') under the other ('2'). This URI is just a
734         string, so it can be passed around through email or other out-of-band
735         protocol.
736         """
737
738     def list():
739         """I return a Deferred that fires with a dictionary mapping child
740         name (a unicode string) to (node, metadata_dict) tuples, in which
741         'node' is either an IFileNode or IDirectoryNode, and 'metadata_dict'
742         is a dictionary of metadata."""
743
744     def has_child(name):
745         """I return a Deferred that fires with a boolean, True if there
746         exists a child of the given name, False if not. The child name must
747         be a unicode string."""
748
749     def get(name):
750         """I return a Deferred that fires with a specific named child node,
751         either an IFileNode or an IDirectoryNode. The child name must be a
752         unicode string. I raise NoSuchChildError if I do not have a child by
753         that name."""
754
755     def get_metadata_for(name):
756         """I return a Deferred that fires with the metadata dictionary for a
757         specific named child node. This metadata is stored in the *edge*, not
758         in the child, so it is attached to the parent dirnode rather than the
759         child dir-or-file-node. The child name must be a unicode string. I
760         raise NoSuchChildError if I do not have a child by that name."""
761
762     def set_metadata_for(name, metadata):
763         """I replace any existing metadata for the named child with the new
764         metadata. The child name must be a unicode string. This metadata is
765         stored in the *edge*, not in the child, so it is attached to the
766         parent dirnode rather than the child dir-or-file-node. I return a
767         Deferred (that fires with this dirnode) when the operation is
768         complete. I raise NoSuchChildError if I do not have a child by that
769         name."""
770
771     def get_child_at_path(path):
772         """Transform a child path into an IDirectoryNode or IFileNode.
773
774         I perform a recursive series of 'get' operations to find the named
775         descendant node. I return a Deferred that fires with the node, or
776         errbacks with NoSuchChildError if the node could not be found.
777
778         The path can be either a single string (slash-separated) or a list of
779         path-name elements. All elements must be unicode strings.
780         """
781
782     def get_child_and_metadata_at_path(path):
783         """Transform a child path into an IDirectoryNode/IFileNode and
784         metadata.
785
786         I am like get_child_at_path(), but my Deferred fires with a tuple of
787         (node, metadata). The metadata comes from the last edge. If the path
788         is empty, the metadata will be an empty dictionary.
789         """
790
791     def set_uri(name, child_uri, metadata=None, overwrite=True):
792         """I add a child (by URI) at the specific name. I return a Deferred
793         that fires when the operation finishes. If overwrite= is True, I will
794         replace any existing child of the same name, otherwise an existing
795         child will cause me to return ExistingChildError. The child name must
796         be a unicode string.
797
798         The child_uri could be for a file, or for a directory (either
799         read-write or read-only, using a URI that came from get_uri() ).
800
801         If metadata= is provided, I will use it as the metadata for the named
802         edge. This will replace any existing metadata. If metadata= is left
803         as the default value of None, I will set ['mtime'] to the current
804         time, and I will set ['ctime'] to the current time if there was not
805         already a child by this name present. This roughly matches the
806         ctime/mtime semantics of traditional filesystems.
807
808         If this directory node is read-only, the Deferred will errback with a
809         NotMutableError."""
810
811     def set_children(entries, overwrite=True):
812         """Add multiple (name, child_uri) pairs (or (name, child_uri,
813         metadata) triples) to a directory node. Returns a Deferred that fires
814         (with None) when the operation finishes. This is equivalent to
815         calling set_uri() multiple times, but is much more efficient. All
816         child names must be unicode strings.
817         """
818
819     def set_node(name, child, metadata=None, overwrite=True):
820         """I add a child at the specific name. I return a Deferred that fires
821         when the operation finishes. This Deferred will fire with the child
822         node that was just added. I will replace any existing child of the
823         same name. The child name must be a unicode string. The 'child'
824         instance must be an instance providing IDirectoryNode or IFileNode.
825
826         If metadata= is provided, I will use it as the metadata for the named
827         edge. This will replace any existing metadata. If metadata= is left
828         as the default value of None, I will set ['mtime'] to the current
829         time, and I will set ['ctime'] to the current time if there was not
830         already a child by this name present. This roughly matches the
831         ctime/mtime semantics of traditional filesystems.
832
833         If this directory node is read-only, the Deferred will errback with a
834         NotMutableError."""
835
836     def set_nodes(entries, overwrite=True):
837         """Add multiple (name, child_node) pairs (or (name, child_node,
838         metadata) triples) to a directory node. Returns a Deferred that fires
839         (with None) when the operation finishes. This is equivalent to
840         calling set_node() multiple times, but is much more efficient. All
841         child names must be unicode strings."""
842
843
844     def add_file(name, uploadable, metadata=None, overwrite=True):
845         """I upload a file (using the given IUploadable), then attach the
846         resulting FileNode to the directory at the given name. I set metadata
847         the same way as set_uri and set_node. The child name must be a
848         unicode string.
849
850         I return a Deferred that fires (with the IFileNode of the uploaded
851         file) when the operation completes."""
852
853     def delete(name):
854         """I remove the child at the specific name. I return a Deferred that
855         fires when the operation finishes. The child name must be a unicode
856         string. I raise NoSuchChildError if I do not have a child by that
857         name."""
858
859     def create_empty_directory(name, overwrite=True):
860         """I create and attach an empty directory at the given name. The
861         child name must be a unicode string. I return a Deferred that fires
862         when the operation finishes."""
863
864     def move_child_to(current_child_name, new_parent, new_child_name=None,
865                       overwrite=True):
866         """I take one of my children and move them to a new parent. The child
867         is referenced by name. On the new parent, the child will live under
868         'new_child_name', which defaults to 'current_child_name'. TODO: what
869         should we do about metadata? I return a Deferred that fires when the
870         operation finishes. The child name must be a unicode string. I raise
871         NoSuchChildError if I do not have a child by that name."""
872
873     def build_manifest():
874         """I generate a table of everything reachable from this directory.
875         I also compute deep-stats as described below.
876
877         I return a Monitor. The Monitor's results will be a dictionary with
878         two elements. The 'manifest' element is a list of (path, cap) tuples
879         for nodes (directories and files) reachable from this one. 'path'
880         will be a tuple of unicode strings. The origin dirnode will be
881         represented by an empty path tuple. The 'stats' element is a
882         dictionary, the same that is generated by start_deep_stats() below.
883
884         The Monitor will also have an .origin_si attribute with the (binary)
885         storage index of the starting point.
886         """
887
888     def start_deep_stats():
889         """Return a Monitor, examining all nodes (directories and files)
890         reachable from this one. The Monitor's results will be a dictionary
891         with the following keys::
892
893            count-immutable-files: count of how many CHK files are in the set
894            count-mutable-files: same, for mutable files (does not include
895                                 directories)
896            count-literal-files: same, for LIT files
897            count-files: sum of the above three
898
899            count-directories: count of directories
900
901            size-immutable-files: total bytes for all CHK files in the set
902            size-mutable-files (TODO): same, for current version of all mutable
903                                       files, does not include directories
904            size-literal-files: same, for LIT files
905            size-directories: size of mutable files used by directories
906
907            largest-directory: number of bytes in the largest directory
908            largest-directory-children: number of children in the largest
909                                        directory
910            largest-immutable-file: number of bytes in the largest CHK file
911
912         size-mutable-files is not yet implemented, because it would involve
913         even more queries than deep_stats does.
914
915         The Monitor will also have an .origin_si attribute with the (binary)
916         storage index of the starting point.
917
918         This operation will visit every directory node underneath this one,
919         and can take a long time to run. On a typical workstation with good
920         bandwidth, this can examine roughly 15 directories per second (and
921         takes several minutes of 100% CPU for ~1700 directories).
922         """
923
924 class ICodecEncoder(Interface):
925     def set_params(data_size, required_shares, max_shares):
926         """Set up the parameters of this encoder.
927
928         This prepares the encoder to perform an operation that converts a
929         single block of data into a number of shares, such that a future
930         ICodecDecoder can use a subset of these shares to recover the
931         original data. This operation is invoked by calling encode(). Once
932         the encoding parameters are set up, the encode operation can be
933         invoked multiple times.
934
935         set_params() prepares the encoder to accept blocks of input data that
936         are exactly 'data_size' bytes in length. The encoder will be prepared
937         to produce 'max_shares' shares for each encode() operation (although
938         see the 'desired_share_ids' to use less CPU). The encoding math will
939         be chosen such that the decoder can get by with as few as
940         'required_shares' of these shares and still reproduce the original
941         data. For example, set_params(1000, 5, 5) offers no redundancy at
942         all, whereas set_params(1000, 1, 10) provides 10x redundancy.
943
944         Numerical Restrictions: 'data_size' is required to be an integral
945         multiple of 'required_shares'. In general, the caller should choose
946         required_shares and max_shares based upon their reliability
947         requirements and the number of peers available (the total storage
948         space used is roughly equal to max_shares*data_size/required_shares),
949         then choose data_size to achieve the memory footprint desired (larger
950         data_size means more efficient operation, smaller data_size means
951         smaller memory footprint).
952
953         In addition, 'max_shares' must be equal to or greater than
954         'required_shares'. Of course, setting them to be equal causes
955         encode() to degenerate into a particularly slow form of the 'split'
956         utility.
957
958         See encode() for more details about how these parameters are used.
959
960         set_params() must be called before any other ICodecEncoder methods
961         may be invoked.
962         """
963
964     def get_encoder_type():
965         """Return a short string that describes the type of this encoder.
966
967         There is required to be a global table of encoder classes. This method
968         returns an index into this table; the value at this index is an
969         encoder class, and this encoder is an instance of that class.
970         """
971
972     def get_serialized_params(): # TODO: maybe, maybe not
973         """Return a string that describes the parameters of this encoder.
974
975         This string can be passed to the decoder to prepare it for handling
976         the encoded shares we create. It might contain more information than
977         was presented to set_params(), if there is some flexibility of
978         parameter choice.
979
980         This string is intended to be embedded in the URI, so there are
981         several restrictions on its contents. At the moment I'm thinking that
982         this means it may contain hex digits and hyphens, and nothing else.
983         The idea is that the URI contains something like '%s:%s:%s' %
984         (encoder.get_encoder_name(), encoder.get_serialized_params(),
985         b2a(crypttext_hash)), and this is enough information to construct a
986         compatible decoder.
987         """
988
989     def get_block_size():
990         """Return the length of the shares that encode() will produce.
991         """
992
993     def encode_proposal(data, desired_share_ids=None):
994         """Encode some data.
995
996         'data' must be a string (or other buffer object), and len(data) must
997         be equal to the 'data_size' value passed earlier to set_params().
998
999         This will return a Deferred that will fire with two lists. The first
1000         is a list of shares, each of which is a string (or other buffer
1001         object) such that len(share) is the same as what get_share_size()
1002         returned earlier. The second is a list of shareids, in which each is
1003         an integer. The lengths of the two lists will always be equal to each
1004         other. The user should take care to keep each share closely
1005         associated with its shareid, as one is useless without the other.
1006
1007         The length of this output list will normally be the same as the value
1008         provided to the 'max_shares' parameter of set_params(). This may be
1009         different if 'desired_share_ids' is provided.
1010
1011         'desired_share_ids', if provided, is required to be a sequence of
1012         ints, each of which is required to be >= 0 and < max_shares. If not
1013         provided, encode() will produce 'max_shares' shares, as if
1014         'desired_share_ids' were set to range(max_shares). You might use this
1015         if you initially thought you were going to use 10 peers, started
1016         encoding, and then two of the peers dropped out: you could use
1017         desired_share_ids= to skip the work (both memory and CPU) of
1018         producing shares for the peers which are no longer available.
1019
1020         """
1021
1022     def encode(inshares, desired_share_ids=None):
1023         """Encode some data. This may be called multiple times. Each call is
1024         independent.
1025
1026         inshares is a sequence of length required_shares, containing buffers
1027         (i.e. strings), where each buffer contains the next contiguous
1028         non-overlapping segment of the input data. Each buffer is required to
1029         be the same length, and the sum of the lengths of the buffers is
1030         required to be exactly the data_size promised by set_params(). (This
1031         implies that the data has to be padded before being passed to
1032         encode(), unless of course it already happens to be an even multiple
1033         of required_shares in length.)
1034
1035          ALSO: the requirement to break up your data into 'required_shares'
1036          chunks before calling encode() feels a bit surprising, at least from
1037          the point of view of a user who doesn't know how FEC works. It feels
1038          like an implementation detail that has leaked outside the
1039          abstraction barrier. Can you imagine a use case in which the data to
1040          be encoded might already be available in pre-segmented chunks, such
1041          that it is faster or less work to make encode() take a list rather
1042          than splitting a single string?
1043
1044          ALSO ALSO: I think 'inshares' is a misleading term, since encode()
1045          is supposed to *produce* shares, so what it *accepts* should be
1046          something other than shares. Other places in this interface use the
1047          word 'data' for that-which-is-not-shares.. maybe we should use that
1048          term?
1049
1050         'desired_share_ids', if provided, is required to be a sequence of
1051         ints, each of which is required to be >= 0 and < max_shares. If not
1052         provided, encode() will produce 'max_shares' shares, as if
1053         'desired_share_ids' were set to range(max_shares). You might use this
1054         if you initially thought you were going to use 10 peers, started
1055         encoding, and then two of the peers dropped out: you could use
1056         desired_share_ids= to skip the work (both memory and CPU) of
1057         producing shares for the peers which are no longer available.
1058
1059         For each call, encode() will return a Deferred that fires with two
1060         lists, one containing shares and the other containing the shareids.
1061         The get_share_size() method can be used to determine the length of
1062         the share strings returned by encode(). Each shareid is a small
1063         integer, exactly as passed into 'desired_share_ids' (or
1064         range(max_shares), if desired_share_ids was not provided).
1065
1066         The shares and their corresponding shareids are required to be kept
1067         together during storage and retrieval. Specifically, the share data is
1068         useless by itself: the decoder needs to be told which share is which
1069         by providing it with both the shareid and the actual share data.
1070
1071         This function will allocate an amount of memory roughly equal to::
1072
1073          (max_shares - required_shares) * get_share_size()
1074
1075         When combined with the memory that the caller must allocate to
1076         provide the input data, this leads to a memory footprint roughly
1077         equal to the size of the resulting encoded shares (i.e. the expansion
1078         factor times the size of the input segment).
1079         """
1080
1081         # rejected ideas:
1082         #
1083         #  returning a list of (shareidN,shareN) tuples instead of a pair of
1084         #  lists (shareids..,shares..). Brian thought the tuples would
1085         #  encourage users to keep the share and shareid together throughout
1086         #  later processing, Zooko pointed out that the code to iterate
1087         #  through two lists is not really more complicated than using a list
1088         #  of tuples and there's also a performance improvement
1089         #
1090         #  having 'data_size' not required to be an integral multiple of
1091         #  'required_shares'. Doing this would require encode() to perform
1092         #  padding internally, and we'd prefer to have any padding be done
1093         #  explicitly by the caller. Yes, it is an abstraction leak, but
1094         #  hopefully not an onerous one.
1095
1096
1097 class ICodecDecoder(Interface):
1098     def set_serialized_params(params):
1099         """Set up the parameters of this encoder, from a string returned by
1100         encoder.get_serialized_params()."""
1101
1102     def get_needed_shares():
1103         """Return the number of shares needed to reconstruct the data.
1104         set_serialized_params() is required to be called before this."""
1105
1106     def decode(some_shares, their_shareids):
1107         """Decode a partial list of shares into data.
1108
1109         'some_shares' is required to be a sequence of buffers of sharedata, a
1110         subset of the shares returned by ICodecEncode.encode(). Each share is
1111         required to be of the same length.  The i'th element of their_shareids
1112         is required to be the shareid of the i'th buffer in some_shares.
1113
1114         This returns a Deferred which fires with a sequence of buffers. This
1115         sequence will contain all of the segments of the original data, in
1116         order. The sum of the lengths of all of the buffers will be the
1117         'data_size' value passed into the original ICodecEncode.set_params()
1118         call. To get back the single original input block of data, use
1119         ''.join(output_buffers), or you may wish to simply write them in
1120         order to an output file.
1121
1122         Note that some of the elements in the result sequence may be
1123         references to the elements of the some_shares input sequence. In
1124         particular, this means that if those share objects are mutable (e.g.
1125         arrays) and if they are changed, then both the input (the
1126         'some_shares' parameter) and the output (the value given when the
1127         deferred is triggered) will change.
1128
1129         The length of 'some_shares' is required to be exactly the value of
1130         'required_shares' passed into the original ICodecEncode.set_params()
1131         call.
1132         """
1133
1134 class IEncoder(Interface):
1135     """I take an object that provides IEncryptedUploadable, which provides
1136     encrypted data, and a list of shareholders. I then encode, hash, and
1137     deliver shares to those shareholders. I will compute all the necessary
1138     Merkle hash trees that are necessary to validate the crypttext that
1139     eventually comes back from the shareholders. I provide the URI Extension
1140     Block Hash, and the encoding parameters, both of which must be included
1141     in the URI.
1142
1143     I do not choose shareholders, that is left to the IUploader. I must be
1144     given a dict of RemoteReferences to storage buckets that are ready and
1145     willing to receive data.
1146     """
1147
1148     def set_size(size):
1149         """Specify the number of bytes that will be encoded. This must be
1150         peformed before get_serialized_params() can be called.
1151         """
1152     def set_params(params):
1153         """Override the default encoding parameters. 'params' is a tuple of
1154         (k,d,n), where 'k' is the number of required shares, 'd' is the
1155         shares_of_happiness, and 'n' is the total number of shares that will
1156         be created.
1157
1158         Encoding parameters can be set in three ways. 1: The Encoder class
1159         provides defaults (3/7/10). 2: the Encoder can be constructed with
1160         an 'options' dictionary, in which the
1161         needed_and_happy_and_total_shares' key can be a (k,d,n) tuple. 3:
1162         set_params((k,d,n)) can be called.
1163
1164         If you intend to use set_params(), you must call it before
1165         get_share_size or get_param are called.
1166         """
1167
1168     def set_encrypted_uploadable(u):
1169         """Provide a source of encrypted upload data. 'u' must implement
1170         IEncryptedUploadable.
1171
1172         When this is called, the IEncryptedUploadable will be queried for its
1173         length and the storage_index that should be used.
1174
1175         This returns a Deferred that fires with this Encoder instance.
1176
1177         This must be performed before start() can be called.
1178         """
1179
1180     def get_param(name):
1181         """Return an encoding parameter, by name.
1182
1183         'storage_index': return a string with the (16-byte truncated SHA-256
1184                          hash) storage index to which these shares should be
1185                          pushed.
1186
1187         'share_counts': return a tuple describing how many shares are used:
1188                         (needed_shares, shares_of_happiness, total_shares)
1189
1190         'num_segments': return an int with the number of segments that
1191                         will be encoded.
1192
1193         'segment_size': return an int with the size of each segment.
1194
1195         'block_size': return the size of the individual blocks that will
1196                       be delivered to a shareholder's put_block() method. By
1197                       knowing this, the shareholder will be able to keep all
1198                       blocks in a single file and still provide random access
1199                       when reading them. # TODO: can we avoid exposing this?
1200
1201         'share_size': an int with the size of the data that will be stored
1202                       on each shareholder. This is aggregate amount of data
1203                       that will be sent to the shareholder, summed over all
1204                       the put_block() calls I will ever make. It is useful to
1205                       determine this size before asking potential
1206                       shareholders whether they will grant a lease or not,
1207                       since their answers will depend upon how much space we
1208                       need. TODO: this might also include some amount of
1209                       overhead, like the size of all the hashes. We need to
1210                       decide whether this is useful or not.
1211
1212         'serialized_params': a string with a concise description of the
1213                              codec name and its parameters. This may be passed
1214                              into the IUploadable to let it make sure that
1215                              the same file encoded with different parameters
1216                              will result in different storage indexes.
1217
1218         Once this is called, set_size() and set_params() may not be called.
1219         """
1220
1221     def set_shareholders(shareholders):
1222         """Tell the encoder where to put the encoded shares. 'shareholders'
1223         must be a dictionary that maps share number (an integer ranging from
1224         0 to n-1) to an instance that provides IStorageBucketWriter. This
1225         must be performed before start() can be called."""
1226
1227     def start():
1228         """Begin the encode/upload process. This involves reading encrypted
1229         data from the IEncryptedUploadable, encoding it, uploading the shares
1230         to the shareholders, then sending the hash trees.
1231
1232         set_encrypted_uploadable() and set_shareholders() must be called
1233         before this can be invoked.
1234
1235         This returns a Deferred that fires with a tuple of
1236         (uri_extension_hash, needed_shares, total_shares, size) when the
1237         upload process is complete. This information, plus the encryption
1238         key, is sufficient to construct the URI.
1239         """
1240
1241 class IDecoder(Interface):
1242     """I take a list of shareholders and some setup information, then
1243     download, validate, decode, and decrypt data from them, writing the
1244     results to an output file.
1245
1246     I do not locate the shareholders, that is left to the IDownloader. I must
1247     be given a dict of RemoteReferences to storage buckets that are ready to
1248     send data.
1249     """
1250
1251     def setup(outfile):
1252         """I take a file-like object (providing write and close) to which all
1253         the plaintext data will be written.
1254
1255         TODO: producer/consumer . Maybe write() should return a Deferred that
1256         indicates when it will accept more data? But probably having the
1257         IDecoder be a producer is easier to glue to IConsumer pieces.
1258         """
1259
1260     def set_shareholders(shareholders):
1261         """I take a dictionary that maps share identifiers (small integers)
1262         to RemoteReferences that provide RIBucketReader. This must be called
1263         before start()."""
1264
1265     def start():
1266         """I start the download. This process involves retrieving data and
1267         hash chains from the shareholders, using the hashes to validate the
1268         data, decoding the shares into segments, decrypting the segments,
1269         then writing the resulting plaintext to the output file.
1270
1271         I return a Deferred that will fire (with self) when the download is
1272         complete.
1273         """
1274
1275 class IDownloadTarget(Interface):
1276     # Note that if the IDownloadTarget is also an IConsumer, the downloader
1277     # will register itself as a producer. This allows the target to invoke
1278     # downloader.pauseProducing, resumeProducing, and stopProducing.
1279     def open(size):
1280         """Called before any calls to write() or close(). If an error
1281         occurs before any data is available, fail() may be called without
1282         a previous call to open().
1283
1284         'size' is the length of the file being downloaded, in bytes."""
1285
1286     def write(data):
1287         """Output some data to the target."""
1288     def close():
1289         """Inform the target that there is no more data to be written."""
1290     def fail(why):
1291         """fail() is called to indicate that the download has failed. 'why'
1292         is a Failure object indicating what went wrong. No further methods
1293         will be invoked on the IDownloadTarget after fail()."""
1294     def register_canceller(cb):
1295         """The FileDownloader uses this to register a no-argument function
1296         that the target can call to cancel the download. Once this canceller
1297         is invoked, no further calls to write() or close() will be made."""
1298     def finish():
1299         """When the FileDownloader is done, this finish() function will be
1300         called. Whatever it returns will be returned to the invoker of
1301         Downloader.download.
1302         """
1303
1304 class IDownloader(Interface):
1305     def download(uri, target):
1306         """Perform a CHK download, sending the data to the given target.
1307         'target' must provide IDownloadTarget.
1308
1309         Returns a Deferred that fires (with the results of target.finish)
1310         when the download is finished, or errbacks if something went wrong."""
1311
1312 class IEncryptedUploadable(Interface):
1313     def set_upload_status(upload_status):
1314         """Provide an IUploadStatus object that should be filled with status
1315         information. The IEncryptedUploadable is responsible for setting
1316         key-determination progress ('chk'), size, storage_index, and
1317         ciphertext-fetch progress. It may delegate some of this
1318         responsibility to others, in particular to the IUploadable."""
1319
1320     def get_size():
1321         """This behaves just like IUploadable.get_size()."""
1322
1323     def get_all_encoding_parameters():
1324         """Return a Deferred that fires with a tuple of
1325         (k,happy,n,segment_size). The segment_size will be used as-is, and
1326         must match the following constraints: it must be a multiple of k, and
1327         it shouldn't be unreasonably larger than the file size (if
1328         segment_size is larger than filesize, the difference must be stored
1329         as padding).
1330
1331         This usually passes through to the IUploadable method of the same
1332         name.
1333
1334         The encoder strictly obeys the values returned by this method. To
1335         make an upload use non-default encoding parameters, you must arrange
1336         to control the values that this method returns.
1337         """
1338
1339     def get_storage_index():
1340         """Return a Deferred that fires with a 16-byte storage index.
1341         """
1342
1343     def read_encrypted(length, hash_only):
1344         """This behaves just like IUploadable.read(), but returns crypttext
1345         instead of plaintext. If hash_only is True, then this discards the
1346         data (and returns an empty list); this improves efficiency when
1347         resuming an interrupted upload (where we need to compute the
1348         plaintext hashes, but don't need the redundant encrypted data)."""
1349
1350     def get_plaintext_hashtree_leaves(first, last, num_segments):
1351         """Get the leaf nodes of a merkle hash tree over the plaintext
1352         segments, i.e. get the tagged hashes of the given segments. The
1353         segment size is expected to be generated by the IEncryptedUploadable
1354         before any plaintext is read or ciphertext produced, so that the
1355         segment hashes can be generated with only a single pass.
1356
1357         This returns a Deferred which fires with a sequence of hashes, using:
1358
1359          tuple(segment_hashes[first:last])
1360
1361         'num_segments' is used to assert that the number of segments that the
1362         IEncryptedUploadable handled matches the number of segments that the
1363         encoder was expecting.
1364
1365         This method must not be called until the final byte has been read
1366         from read_encrypted(). Once this method is called, read_encrypted()
1367         can never be called again.
1368         """
1369
1370     def get_plaintext_hash():
1371         """Get the hash of the whole plaintext.
1372
1373         This returns a Deferred which fires with a tagged SHA-256 hash of the
1374         whole plaintext, obtained from hashutil.plaintext_hash(data).
1375         """
1376
1377     def close():
1378         """Just like IUploadable.close()."""
1379
1380 class IUploadable(Interface):
1381     def set_upload_status(upload_status):
1382         """Provide an IUploadStatus object that should be filled with status
1383         information. The IUploadable is responsible for setting
1384         key-determination progress ('chk')."""
1385
1386     def set_default_encoding_parameters(params):
1387         """Set the default encoding parameters, which must be a dict mapping
1388         strings to ints. The meaningful keys are 'k', 'happy', 'n', and
1389         'max_segment_size'. These might have an influence on the final
1390         encoding parameters returned by get_all_encoding_parameters(), if the
1391         Uploadable doesn't have more specific preferences.
1392
1393         This call is optional: if it is not used, the Uploadable will use
1394         some built-in defaults. If used, this method must be called before
1395         any other IUploadable methods to have any effect.
1396         """
1397
1398     def get_size():
1399         """Return a Deferred that will fire with the length of the data to be
1400         uploaded, in bytes. This will be called before the data is actually
1401         used, to compute encoding parameters.
1402         """
1403
1404     def get_all_encoding_parameters():
1405         """Return a Deferred that fires with a tuple of
1406         (k,happy,n,segment_size). The segment_size will be used as-is, and
1407         must match the following constraints: it must be a multiple of k, and
1408         it shouldn't be unreasonably larger than the file size (if
1409         segment_size is larger than filesize, the difference must be stored
1410         as padding).
1411
1412         The relative values of k and n allow some IUploadables to request
1413         better redundancy than others (in exchange for consuming more space
1414         in the grid).
1415
1416         Larger values of segment_size reduce hash overhead, while smaller
1417         values reduce memory footprint and cause data to be delivered in
1418         smaller pieces (which may provide a smoother and more predictable
1419         download experience).
1420
1421         The encoder strictly obeys the values returned by this method. To
1422         make an upload use non-default encoding parameters, you must arrange
1423         to control the values that this method returns. One way to influence
1424         them may be to call set_encoding_parameters() before calling
1425         get_all_encoding_parameters().
1426         """
1427
1428     def get_encryption_key():
1429         """Return a Deferred that fires with a 16-byte AES key. This key will
1430         be used to encrypt the data. The key will also be hashed to derive
1431         the StorageIndex.
1432
1433         Uploadables which want to achieve convergence should hash their file
1434         contents and the serialized_encoding_parameters to form the key
1435         (which of course requires a full pass over the data). Uploadables can
1436         use the upload.ConvergentUploadMixin class to achieve this
1437         automatically.
1438
1439         Uploadables which do not care about convergence (or do not wish to
1440         make multiple passes over the data) can simply return a
1441         strongly-random 16 byte string.
1442
1443         get_encryption_key() may be called multiple times: the IUploadable is
1444         required to return the same value each time.
1445         """
1446
1447     def read(length):
1448         """Return a Deferred that fires with a list of strings (perhaps with
1449         only a single element) which, when concatenated together, contain the
1450         next 'length' bytes of data. If EOF is near, this may provide fewer
1451         than 'length' bytes. The total number of bytes provided by read()
1452         before it signals EOF must equal the size provided by get_size().
1453
1454         If the data must be acquired through multiple internal read
1455         operations, returning a list instead of a single string may help to
1456         reduce string copies.
1457
1458         'length' will typically be equal to (min(get_size(),1MB)/req_shares),
1459         so a 10kB file means length=3kB, 100kB file means length=30kB,
1460         and >=1MB file means length=300kB.
1461
1462         This method provides for a single full pass through the data. Later
1463         use cases may desire multiple passes or access to only parts of the
1464         data (such as a mutable file making small edits-in-place). This API
1465         will be expanded once those use cases are better understood.
1466         """
1467
1468     def close():
1469         """The upload is finished, and whatever filehandle was in use may be
1470         closed."""
1471
1472 class IUploadResults(Interface):
1473     """I am returned by upload() methods. I contain a number of public
1474     attributes which can be read to determine the results of the upload. Some
1475     of these are functional, some are timing information. All of these may be
1476     None.::
1477
1478      .file_size : the size of the file, in bytes
1479      .uri : the CHK read-cap for the file
1480      .ciphertext_fetched : how many bytes were fetched by the helper
1481      .sharemap : dict mapping share number to placement string
1482      .servermap : dict mapping server peerid to a set of share numbers
1483      .timings : dict of timing information, mapping name to seconds (float)
1484        total : total upload time, start to finish
1485        storage_index : time to compute the storage index
1486        peer_selection : time to decide which peers will be used
1487        contacting_helper : initial helper query to upload/no-upload decision
1488        existence_check : helper pre-upload existence check
1489        helper_total : initial helper query to helper finished pushing
1490        cumulative_fetch : helper waiting for ciphertext requests
1491        total_fetch : helper start to last ciphertext response
1492        cumulative_encoding : just time spent in zfec
1493        cumulative_sending : just time spent waiting for storage servers
1494        hashes_and_close : last segment push to shareholder close
1495        total_encode_and_push : first encode to shareholder close
1496
1497     """
1498
1499 class IDownloadResults(Interface):
1500     """I am created internally by download() methods. I contain a number of
1501     public attributes which contain details about the download process.::
1502
1503      .file_size : the size of the file, in bytes
1504      .servers_used : set of server peerids that were used during download
1505      .server_problems : dict mapping server peerid to a problem string. Only
1506                         servers that had problems (bad hashes, disconnects) are
1507                         listed here.
1508      .servermap : dict mapping server peerid to a set of share numbers. Only
1509                   servers that had any shares are listed here.
1510      .timings : dict of timing information, mapping name to seconds (float)
1511        peer_selection : time to ask servers about shares
1512        servers_peer_selection : dict of peerid to DYHB-query time
1513        uri_extension : time to fetch a copy of the URI extension block
1514        hashtrees : time to fetch the hash trees
1515        segments : time to fetch, decode, and deliver segments
1516        cumulative_fetch : time spent waiting for storage servers
1517        cumulative_decode : just time spent in zfec
1518        cumulative_decrypt : just time spent in decryption
1519        total : total download time, start to finish
1520        fetch_per_server : dict of peerid to list of per-segment fetch times
1521
1522     """
1523
1524 class IUploader(Interface):
1525     def upload(uploadable):
1526         """Upload the file. 'uploadable' must impement IUploadable. This
1527         returns a Deferred which fires with an UploadResults instance, from
1528         which the URI of the file can be obtained as results.uri ."""
1529
1530     def upload_ssk(write_capability, new_version, uploadable):
1531         """TODO: how should this work?"""
1532
1533 class ICheckable(Interface):
1534     def check(monitor, verify=False):
1535         """Check upon my health, optionally repairing any problems.
1536
1537         This returns a Deferred that fires with an instance that provides
1538         ICheckerResults, or None if the object is non-distributed (i.e. LIT
1539         files).
1540
1541         The monitor will be checked periodically to see if the operation has
1542         been cancelled. If so, no new queries will be sent, and the Deferred
1543         will fire (with a OperationCancelledError) immediately.
1544
1545         Filenodes and dirnodes (which provide IFilesystemNode) are also
1546         checkable. Instances that represent verifier-caps will be checkable
1547         but not downloadable. Some objects (like LIT files) do not actually
1548         live in the grid, and their checkers return None (non-distributed
1549         files are always healthy).
1550
1551         If verify=False, a relatively lightweight check will be performed: I
1552         will ask all servers if they have a share for me, and I will believe
1553         whatever they say. If there are at least N distinct shares on the
1554         grid, my results will indicate r.is_healthy()==True. This requires a
1555         roundtrip to each server, but does not transfer very much data, so
1556         the network bandwidth is fairly low.
1557
1558         If verify=True, a more resource-intensive check will be performed:
1559         every share will be downloaded, and the hashes will be validated on
1560         every bit. I will ignore any shares that failed their hash checks. If
1561         there are at least N distinct valid shares on the grid, my results
1562         will indicate r.is_healthy()==True. This requires N/k times as much
1563         download bandwidth (and server disk IO) as a regular download. If a
1564         storage server is holding a corrupt share, or is experiencing memory
1565         failures during retrieval, or is malicious or buggy, then
1566         verification will detect the problem, but checking will not.
1567
1568         TODO: any problems seen during checking will be reported to the
1569         health-manager.furl, a centralized object which is responsible for
1570         figuring out why files are unhealthy so corrective action can be
1571         taken.
1572         """
1573
1574     def check_and_repair(monitor, verify=False):
1575         """Like check(), but if the file/directory is not healthy, attempt to
1576         repair the damage.
1577
1578         Any non-healthy result will cause an immediate repair operation, to
1579         generate and upload new shares. After repair, the file will be as
1580         healthy as we can make it. Details about what sort of repair is done
1581         will be put in the check-and-repair results. The Deferred will not
1582         fire until the repair is complete.
1583
1584         This returns a Deferred which fires with an instance of
1585         ICheckAndRepairResults."""
1586
1587 class IDeepCheckable(Interface):
1588     def start_deep_check(verify=False):
1589         """Check upon the health of me and everything I can reach.
1590
1591         This is a recursive form of check(), useable only on dirnodes.
1592
1593         I return a Monitor, with results that are an IDeepCheckResults
1594         object.
1595         """
1596
1597     def start_deep_check_and_repair(verify=False):
1598         """Check upon the health of me and everything I can reach. Repair
1599         anything that isn't healthy.
1600
1601         This is a recursive form of check_and_repair(), useable only on
1602         dirnodes.
1603
1604         I return a Monitor, with results that are an
1605         IDeepCheckAndRepairResults object.
1606         """
1607
1608 class ICheckerResults(Interface):
1609     """I contain the detailed results of a check/verify operation.
1610     """
1611
1612     def get_storage_index():
1613         """Return a string with the (binary) storage index."""
1614     def get_storage_index_string():
1615         """Return a string with the (printable) abbreviated storage index."""
1616     def get_uri():
1617         """Return the (string) URI of the object that was checked."""
1618
1619     def is_healthy():
1620         """Return a boolean, True if the file/dir is fully healthy, False if
1621         it is damaged in any way. Non-distributed LIT files always return
1622         True."""
1623
1624     def is_recoverable():
1625         """Return a boolean, True if the file/dir can be recovered, False if
1626         not. Unrecoverable files are obviously unhealthy. Non-distributed LIT
1627         files always return True."""
1628
1629     def needs_rebalancing():
1630         """Return a boolean, True if the file/dir's reliability could be
1631         improved by moving shares to new servers. Non-distributed LIT files
1632         always returne False."""
1633
1634
1635     def get_data():
1636         """Return a dictionary that describes the state of the file/dir.
1637         Non-distributed LIT files always return an empty dictionary. Normal
1638         files and directories return a dictionary with the following keys
1639         (note that these use base32-encoded strings rather than binary ones)
1640         (also note that for mutable files, these counts are for the 'best'
1641         version)::
1642
1643          count-shares-good: the number of distinct good shares that were found
1644          count-shares-needed: 'k', the number of shares required for recovery
1645          count-shares-expected: 'N', the number of total shares generated
1646          count-good-share-hosts: the number of distinct storage servers with
1647                                  good shares. If this number is less than
1648                                  count-shares-good, then some shares are
1649                                  doubled up, increasing the correlation of
1650                                  failures. This indicates that one or more
1651                                  shares should be moved to an otherwise unused
1652                                  server, if one is available.
1653          count-corrupt-shares: the number of shares with integrity failures
1654          list-corrupt-shares: a list of 'share locators', one for each share
1655                               that was found to be corrupt. Each share
1656                               locator is a list of (serverid, storage_index,
1657                               sharenum).
1658          servers-responding: list of (binary) storage server identifiers,
1659                              one for each server which responded to the share
1660                              query.
1661          sharemap: dict mapping share identifier to list of serverids
1662                    (binary strings). This indicates which servers are holding
1663                    which shares. For immutable files, the shareid is an
1664                    integer (the share number, from 0 to N-1). For mutable
1665                    files, it is a string of the form 'seq%d-%s-sh%d',
1666                    containing the sequence number, the roothash, and the
1667                    share number.
1668
1669         The following keys are most relevant for mutable files, but immutable
1670         files will provide sensible values too::
1671
1672          count-wrong-shares: the number of shares for versions other than the
1673                              'best' one (which is defined as being the
1674                              recoverable version with the highest sequence
1675                              number, then the highest roothash). These are
1676                              either leftover shares from an older version
1677                              (perhaps on a server that was offline when an
1678                              update occurred), shares from an unrecoverable
1679                              newer version, or shares from an alternate
1680                              current version that results from an
1681                              uncoordinated write collision. For a healthy
1682                              file, this will equal 0.
1683
1684          count-recoverable-versions: the number of recoverable versions of
1685                                      the file. For a healthy file, this will
1686                                      equal 1.
1687
1688          count-unrecoverable-versions: the number of unrecoverable versions
1689                                        of the file. For a healthy file, this
1690                                        will be 0.
1691
1692         """
1693
1694     def get_summary():
1695         """Return a string with a brief (one-line) summary of the results."""
1696
1697     def get_report():
1698         """Return a list of strings with more detailed results."""
1699
1700 class ICheckAndRepairResults(Interface):
1701     """I contain the detailed results of a check/verify/repair operation.
1702
1703     The IFilesystemNode.check()/verify()/repair() methods all return
1704     instances that provide ICheckAndRepairResults.
1705     """
1706
1707     def get_storage_index():
1708         """Return a string with the (binary) storage index."""
1709     def get_storage_index_string():
1710         """Return a string with the (printable) abbreviated storage index."""
1711     def get_repair_attempted():
1712         """Return a boolean, True if a repair was attempted."""
1713     def get_repair_successful():
1714         """Return a boolean, True if repair was attempted and the file/dir
1715         was fully healthy afterwards. False if no repair was attempted or if
1716         a repair attempt failed."""
1717     def get_pre_repair_results():
1718         """Return an ICheckerResults instance that describes the state of the
1719         file/dir before any repair was attempted."""
1720     def get_post_repair_results():
1721         """Return an ICheckerResults instance that describes the state of the
1722         file/dir after any repair was attempted. If no repair was attempted,
1723         the pre-repair and post-repair results will be identical."""
1724
1725
1726 class IDeepCheckResults(Interface):
1727     """I contain the results of a deep-check operation.
1728
1729     This is returned by a call to ICheckable.deep_check().
1730     """
1731
1732     def get_root_storage_index_string():
1733         """Return the storage index (abbreviated human-readable string) of
1734         the first object checked."""
1735     def get_counters():
1736         """Return a dictionary with the following keys::
1737
1738              count-objects-checked: count of how many objects were checked
1739              count-objects-healthy: how many of those objects were completely
1740                                     healthy
1741              count-objects-unhealthy: how many were damaged in some way
1742              count-objects-unrecoverable: how many were unrecoverable
1743              count-corrupt-shares: how many shares were found to have
1744                                    corruption, summed over all objects
1745                                    examined
1746         """
1747
1748     def get_corrupt_shares():
1749         """Return a set of (serverid, storage_index, sharenum) for all shares
1750         that were found to be corrupt. Both serverid and storage_index are
1751         binary.
1752         """
1753     def get_all_results():
1754         """Return a dictionary mapping pathname (a tuple of strings, ready to
1755         be slash-joined) to an ICheckerResults instance, one for each object
1756         that was checked."""
1757
1758     def get_results_for_storage_index(storage_index):
1759         """Retrive the ICheckerResults instance for the given (binary)
1760         storage index. Raises KeyError if there are no results for that
1761         storage index."""
1762
1763     def get_stats():
1764         """Return a dictionary with the same keys as
1765         IDirectoryNode.deep_stats()."""
1766
1767 class IDeepCheckAndRepairResults(Interface):
1768     """I contain the results of a deep-check-and-repair operation.
1769
1770     This is returned by a call to ICheckable.deep_check_and_repair().
1771     """
1772
1773     def get_root_storage_index_string():
1774         """Return the storage index (abbreviated human-readable string) of
1775         the first object checked."""
1776     def get_counters():
1777         """Return a dictionary with the following keys::
1778
1779              count-objects-checked: count of how many objects were checked
1780              count-objects-healthy-pre-repair: how many of those objects were
1781                                                completely healthy (before any
1782                                                repair)
1783              count-objects-unhealthy-pre-repair: how many were damaged in
1784                                                  some way
1785              count-objects-unrecoverable-pre-repair: how many were unrecoverable
1786              count-objects-healthy-post-repair: how many of those objects were
1787                                                 completely healthy (after any
1788                                                 repair)
1789              count-objects-unhealthy-post-repair: how many were damaged in
1790                                                   some way
1791              count-objects-unrecoverable-post-repair: how many were
1792                                                       unrecoverable
1793              count-repairs-attempted: repairs were attempted on this many
1794                                       objects. The count-repairs- keys will
1795                                       always be provided, however unless
1796                                       repair=true is present, they will all
1797                                       be zero.
1798              count-repairs-successful: how many repairs resulted in healthy
1799                                        objects
1800              count-repairs-unsuccessful: how many repairs resulted did not
1801                                          results in completely healthy objects
1802              count-corrupt-shares-pre-repair: how many shares were found to
1803                                               have corruption, summed over all
1804                                               objects examined (before any
1805                                               repair)
1806              count-corrupt-shares-post-repair: how many shares were found to
1807                                                have corruption, summed over all
1808                                                objects examined (after any
1809                                                repair)
1810         """
1811
1812     def get_stats():
1813         """Return a dictionary with the same keys as
1814         IDirectoryNode.deep_stats()."""
1815
1816     def get_corrupt_shares():
1817         """Return a set of (serverid, storage_index, sharenum) for all shares
1818         that were found to be corrupt before any repair was attempted. Both
1819         serverid and storage_index are binary.
1820         """
1821     def get_remaining_corrupt_shares():
1822         """Return a set of (serverid, storage_index, sharenum) for all shares
1823         that were found to be corrupt after any repair was completed. Both
1824         serverid and storage_index are binary. These are shares that need
1825         manual inspection and probably deletion.
1826         """
1827     def get_all_results():
1828         """Return a dictionary mapping pathname (a tuple of strings, ready to
1829         be slash-joined) to an ICheckAndRepairResults instance, one for each
1830         object that was checked."""
1831
1832
1833 class IRepairable(Interface):
1834     def repair(checker_results):
1835         """Attempt to repair the given object. Returns a Deferred that fires
1836         with a IRepairResults object.
1837
1838         I must be called with an object that implements ICheckerResults, as
1839         proof that you have actually discovered a problem with this file. I
1840         will use the data in the checker results to guide the repair process,
1841         such as which servers provided bad data and should therefore be
1842         avoided. The ICheckerResults object is inside the
1843         ICheckAndRepairResults object, which is returned by the
1844         ICheckable.check() method::
1845
1846          d = filenode.check(repair=False)
1847          def _got_results(check_and_repair_results):
1848              check_results = check_and_repair_results.get_pre_repair_results()
1849              return filenode.repair(check_results)
1850          d.addCallback(_got_results)
1851          return d
1852         """
1853
1854 class IRepairResults(Interface):
1855     """I contain the results of a repair operation."""
1856
1857
1858 class IClient(Interface):
1859     def upload(uploadable):
1860         """Upload some data into a CHK, get back the UploadResults for it.
1861         @param uploadable: something that implements IUploadable
1862         @return: a Deferred that fires with the UploadResults instance.
1863                  To get the URI for this file, use results.uri .
1864         """
1865
1866     def create_mutable_file(contents=""):
1867         """Create a new mutable file with contents, get back the URI string.
1868         @param contents: the initial contents to place in the file.
1869         @return: a Deferred that fires with tne (string) SSK URI for the new
1870                  file.
1871         """
1872
1873     def create_empty_dirnode():
1874         """Create a new dirnode, empty and unattached.
1875         @return: a Deferred that fires with the new IDirectoryNode instance.
1876         """
1877
1878     def create_node_from_uri(uri):
1879         """Create a new IFilesystemNode instance from the uri, synchronously.
1880         @param uri: a string or IURI-providing instance. This could be for a
1881                     LiteralFileNode, a CHK file node, a mutable file node, or
1882                     a directory node
1883         @return: an instance that provides IFilesystemNode (or more usefully one
1884                  of its subclasses). File-specifying URIs will result in
1885                  IFileNode or IMutableFileNode -providing instances, like
1886                  FileNode, LiteralFileNode, or MutableFileNode.
1887                  Directory-specifying URIs will result in
1888                  IDirectoryNode-providing instances, like NewDirectoryNode.
1889         """
1890
1891 class IClientStatus(Interface):
1892     def list_all_uploads():
1893         """Return a list of uploader objects, one for each upload which
1894         currently has an object available (tracked with weakrefs). This is
1895         intended for debugging purposes."""
1896     def list_active_uploads():
1897         """Return a list of active IUploadStatus objects."""
1898     def list_recent_uploads():
1899         """Return a list of IUploadStatus objects for the most recently
1900         started uploads."""
1901
1902     def list_all_downloads():
1903         """Return a list of downloader objects, one for each download which
1904         currently has an object available (tracked with weakrefs). This is
1905         intended for debugging purposes."""
1906     def list_active_downloads():
1907         """Return a list of active IDownloadStatus objects."""
1908     def list_recent_downloads():
1909         """Return a list of IDownloadStatus objects for the most recently
1910         started downloads."""
1911
1912 class IUploadStatus(Interface):
1913     def get_started():
1914         """Return a timestamp (float with seconds since epoch) indicating
1915         when the operation was started."""
1916     def get_storage_index():
1917         """Return a string with the (binary) storage index in use on this
1918         upload. Returns None if the storage index has not yet been
1919         calculated."""
1920     def get_size():
1921         """Return an integer with the number of bytes that will eventually
1922         be uploaded for this file. Returns None if the size is not yet known.
1923         """
1924     def using_helper():
1925         """Return True if this upload is using a Helper, False if not."""
1926     def get_status():
1927         """Return a string describing the current state of the upload
1928         process."""
1929     def get_progress():
1930         """Returns a tuple of floats, (chk, ciphertext, encode_and_push),
1931         each from 0.0 to 1.0 . 'chk' describes how much progress has been
1932         made towards hashing the file to determine a CHK encryption key: if
1933         non-convergent encryption is in use, this will be trivial, otherwise
1934         the whole file must be hashed. 'ciphertext' describes how much of the
1935         ciphertext has been pushed to the helper, and is '1.0' for non-helper
1936         uploads. 'encode_and_push' describes how much of the encode-and-push
1937         process has finished: for helper uploads this is dependent upon the
1938         helper providing progress reports. It might be reasonable to add all
1939         three numbers and report the sum to the user."""
1940     def get_active():
1941         """Return True if the upload is currently active, False if not."""
1942     def get_results():
1943         """Return an instance of UploadResults (which contains timing and
1944         sharemap information). Might return None if the upload is not yet
1945         finished."""
1946     def get_counter():
1947         """Each upload status gets a unique number: this method returns that
1948         number. This provides a handle to this particular upload, so a web
1949         page can generate a suitable hyperlink."""
1950
1951 class IDownloadStatus(Interface):
1952     def get_started():
1953         """Return a timestamp (float with seconds since epoch) indicating
1954         when the operation was started."""
1955     def get_storage_index():
1956         """Return a string with the (binary) storage index in use on this
1957         download. This may be None if there is no storage index (i.e. LIT
1958         files)."""
1959     def get_size():
1960         """Return an integer with the number of bytes that will eventually be
1961         retrieved for this file. Returns None if the size is not yet known.
1962         """
1963     def using_helper():
1964         """Return True if this download is using a Helper, False if not."""
1965     def get_status():
1966         """Return a string describing the current state of the download
1967         process."""
1968     def get_progress():
1969         """Returns a float (from 0.0 to 1.0) describing the amount of the
1970         download that has completed. This value will remain at 0.0 until the
1971         first byte of plaintext is pushed to the download target."""
1972     def get_active():
1973         """Return True if the download is currently active, False if not."""
1974     def get_counter():
1975         """Each download status gets a unique number: this method returns
1976         that number. This provides a handle to this particular download, so a
1977         web page can generate a suitable hyperlink."""
1978
1979 class IServermapUpdaterStatus(Interface):
1980     pass
1981 class IPublishStatus(Interface):
1982     pass
1983 class IRetrieveStatus(Interface):
1984     pass
1985
1986 class NotCapableError(Exception):
1987     """You have tried to write to a read-only node."""
1988
1989 class BadWriteEnablerError(Exception):
1990     pass
1991
1992 class RIControlClient(RemoteInterface):
1993
1994     def wait_for_client_connections(num_clients=int):
1995         """Do not return until we have connections to at least NUM_CLIENTS
1996         storage servers.
1997         """
1998
1999     def upload_from_file_to_uri(filename=str, convergence=ChoiceOf(None, StringConstraint(2**20))):
2000         """Upload a file to the grid. This accepts a filename (which must be
2001         absolute) that points to a file on the node's local disk. The node will
2002         read the contents of this file, upload it to the grid, then return the
2003         URI at which it was uploaded.  If convergence is None then a random
2004         encryption key will be used, else the plaintext will be hashed, then
2005         that hash will be mixed together with the "convergence" string to form
2006         the encryption key.
2007         """
2008         return URI
2009
2010     def download_from_uri_to_file(uri=URI, filename=str):
2011         """Download a file from the grid, placing it on the node's local disk
2012         at the given filename (which must be absolute[?]). Returns the
2013         absolute filename where the file was written."""
2014         return str
2015
2016     # debug stuff
2017
2018     def get_memory_usage():
2019         """Return a dict describes the amount of memory currently in use. The
2020         keys are 'VmPeak', 'VmSize', and 'VmData'. The values are integers,
2021         measuring memory consupmtion in bytes."""
2022         return DictOf(str, int)
2023
2024     def speed_test(count=int, size=int, mutable=Any()):
2025         """Write 'count' tempfiles to disk, all of the given size. Measure
2026         how long (in seconds) it takes to upload them all to the servers.
2027         Then measure how long it takes to download all of them. If 'mutable'
2028         is 'create', time creation of mutable files. If 'mutable' is
2029         'upload', then time access to the same mutable file instead of
2030         creating one.
2031
2032         Returns a tuple of (upload_time, download_time).
2033         """
2034         return (float, float)
2035
2036     def measure_peer_response_time():
2037         """Send a short message to each connected peer, and measure the time
2038         it takes for them to respond to it. This is a rough measure of the
2039         application-level round trip time.
2040
2041         @return: a dictionary mapping peerid to a float (RTT time in seconds)
2042         """
2043
2044         return DictOf(Nodeid, float)
2045
2046 UploadResults = Any() #DictOf(str, str)
2047
2048 class RIEncryptedUploadable(RemoteInterface):
2049     __remote_name__ = "RIEncryptedUploadable.tahoe.allmydata.com"
2050
2051     def get_size():
2052         return Offset
2053
2054     def get_all_encoding_parameters():
2055         return (int, int, int, long)
2056
2057     def read_encrypted(offset=Offset, length=ReadSize):
2058         return ListOf(str)
2059
2060     def get_plaintext_hashtree_leaves(first=int, last=int, num_segments=int):
2061         return ListOf(Hash)
2062
2063     def get_plaintext_hash():
2064         return Hash
2065
2066     def close():
2067         return None
2068
2069
2070 class RICHKUploadHelper(RemoteInterface):
2071     __remote_name__ = "RIUploadHelper.tahoe.allmydata.com"
2072
2073     def upload(reader=RIEncryptedUploadable):
2074         return UploadResults
2075
2076
2077 class RIHelper(RemoteInterface):
2078     __remote_name__ = "RIHelper.tahoe.allmydata.com"
2079
2080     def upload_chk(si=StorageIndex):
2081         """See if a file with a given storage index needs uploading. The
2082         helper will ask the appropriate storage servers to see if the file
2083         has already been uploaded. If so, the helper will return a set of
2084         'upload results' that includes whatever hashes are needed to build
2085         the read-cap, and perhaps a truncated sharemap.
2086
2087         If the file has not yet been uploaded (or if it was only partially
2088         uploaded), the helper will return an empty upload-results dictionary
2089         and also an RICHKUploadHelper object that will take care of the
2090         upload process. The client should call upload() on this object and
2091         pass it a reference to an RIEncryptedUploadable object that will
2092         provide ciphertext. When the upload is finished, the upload() method
2093         will finish and return the upload results.
2094         """
2095         return (UploadResults, ChoiceOf(RICHKUploadHelper, None))
2096
2097
2098 class RIStatsProvider(RemoteInterface):
2099     __remote_name__ = "RIStatsProvider.tahoe.allmydata.com"
2100     """
2101     Provides access to statistics and monitoring information.
2102     """
2103
2104     def get_stats():
2105         """
2106         returns a dictionary containing 'counters' and 'stats', each a dictionary
2107         with string counter/stat name keys, and numeric values.  counters are
2108         monotonically increasing measures of work done, and stats are instantaneous
2109         measures (potentially time averaged internally)
2110         """
2111         return DictOf(str, DictOf(str, ChoiceOf(float, int, long)))
2112
2113 class RIStatsGatherer(RemoteInterface):
2114     __remote_name__ = "RIStatsGatherer.tahoe.allmydata.com"
2115     """
2116     Provides a monitoring service for centralised collection of stats
2117     """
2118
2119     def provide(provider=RIStatsProvider, nickname=str):
2120         """
2121         @param provider: a stats collector instance which should be polled
2122                          periodically by the gatherer to collect stats.
2123         @param nickname: a name useful to identify the provided client
2124         """
2125         return None
2126
2127
2128 class IStatsProducer(Interface):
2129     def get_stats():
2130         """
2131         returns a dictionary, with str keys representing the names of stats
2132         to be monitored, and numeric values.
2133         """
2134
2135 class RIKeyGenerator(RemoteInterface):
2136     __remote_name__ = "RIKeyGenerator.tahoe.allmydata.com"
2137     """
2138     Provides a service offering to make RSA key pairs.
2139     """
2140
2141     def get_rsa_key_pair(key_size=int):
2142         """
2143         @param key_size: the size of the signature key.
2144         @return: tuple(verifying_key, signing_key)
2145         """
2146         return TupleOf(str, str)
2147
2148
2149 class FileTooLargeError(Exception):
2150     pass
2151