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