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