]> git.rkrishnan.org Git - tahoe-lafs/tahoe-lafs.git/blobdiff - src/allmydata/interfaces.py
revert previous commit to fix attribution (vanity)
[tahoe-lafs/tahoe-lafs.git] / src / allmydata / interfaces.py
index d2a93e3e37fbc318e324983e8ebf41e7f8b1b56c..e495c759a0e7735833257cce6f1b898679936d1b 100644 (file)
@@ -4,6 +4,10 @@ from foolscap.api import StringConstraint, ListOf, TupleOf, SetOf, DictOf, \
      ChoiceOf, IntegerConstraint, Any, RemoteInterface, Referenceable
 
 HASH_SIZE=32
+SALT_SIZE=16
+
+SDMF_VERSION=0
+MDMF_VERSION=1
 
 Hash = StringConstraint(maxLength=HASH_SIZE,
                         minLength=HASH_SIZE)# binary format 32-byte SHA256 hash
@@ -15,22 +19,17 @@ URI = StringConstraint(300) # kind of arbitrary
 
 MAX_BUCKETS = 256  # per peer -- zfec offers at most 256 shares per file
 
+DEFAULT_MAX_SEGMENT_SIZE = 128*1024
+
 ShareData = StringConstraint(None)
 URIExtensionData = StringConstraint(1000)
 Number = IntegerConstraint(8) # 2**(8*8) == 16EiB ~= 18e18 ~= 18 exabytes
 Offset = Number
 ReadSize = int # the 'int' constraint is 2**31 == 2Gib -- large files are processed in not-so-large increments
-WriteEnablerSecret = Hash # used to protect mutable bucket modifications
-LeaseRenewSecret = Hash # used to protect bucket lease renewal requests
-LeaseCancelSecret = Hash # used to protect bucket lease cancellation requests
-
-class RIStubClient(RemoteInterface):
-    """Each client publishes a service announcement for a dummy object called
-    the StubClient. This object doesn't actually offer any services, but the
-    announcement helps the Introducer keep track of which clients are
-    subscribed (so the grid admin can keep track of things like the size of
-    the grid and the client versions in use. This is the (empty)
-    RemoteInterface for the StubClient."""
+WriteEnablerSecret = Hash # used to protect mutable share modifications
+LeaseRenewSecret = Hash # used to protect lease renewal requests
+LeaseCancelSecret = Hash # was used to protect lease cancellation requests
+
 
 class RIBucketWriter(RemoteInterface):
     """ Objects of this kind live on the server side. """
@@ -50,6 +49,7 @@ class RIBucketWriter(RemoteInterface):
         """
         return None
 
+
 class RIBucketReader(RemoteInterface):
     def read(offset=Offset, length=ReadSize):
         return ShareData
@@ -60,12 +60,13 @@ class RIBucketReader(RemoteInterface):
         failures. I will record their concern so that my operator can
         manually inspect the shares in question. I return None.
 
-        This is a wrapper around RIStorageServer.advise_corrupt_share(),
-        which is tied to a specific share, and therefore does not need the
+        This is a wrapper around RIStorageServer.advise_corrupt_share()
+        that is tied to a specific share, and therefore does not need the
         extra share-identifying arguments. Please see that method for full
         documentation.
         """
 
+
 TestVector = ListOf(TupleOf(Offset, ReadSize, str, str))
 # elements are (offset, length, operator, specimen)
 # operator is one of "lt, le, eq, ne, ge, gt"
@@ -82,6 +83,7 @@ ReadVector = ListOf(TupleOf(Offset, ReadSize))
 ReadData = ListOf(ShareData)
 # returns data[offset:offset+length] for each element of TestVector
 
+
 class RIStorageServer(RemoteInterface):
     __remote_name__ = "RIStorageServer.tahoe.allmydata.com"
 
@@ -106,7 +108,9 @@ class RIStorageServer(RemoteInterface):
                              This secret is generated by the client and
                              stored for later comparison by the server. Each
                              server is given a different secret.
-        @param cancel_secret: Like renew_secret, but protects bucket decref.
+        @param cancel_secret: This no longer allows lease cancellation, but
+                              must still be a unique value identifying the
+                              lease. XXX stop relying on it to be unique.
         @param canary: If the canary is lost before close(), the bucket is
                        deleted.
         @return: tuple of (alreadygot, allocated), where alreadygot is what we
@@ -137,23 +141,8 @@ class RIStorageServer(RemoteInterface):
         For mutable shares, if the given renew_secret does not match an
         existing lease, IndexError will be raised with a note listing the
         server-nodeids on the existing leases, so leases on migrated shares
-        can be renewed or cancelled. For immutable shares, IndexError
-        (without the note) will be raised.
-        """
-        return Any()
-
-    def cancel_lease(storage_index=StorageIndex,
-                     cancel_secret=LeaseCancelSecret):
-        """
-        Cancel the lease on a given bucket. If this was the last lease on the
-        bucket, the bucket will be deleted. If there is no bucket for the
-        given storage_index, IndexError will be raised.
-
-        For mutable shares, if the given cancel_secret does not match an
-        existing lease, IndexError will be raised with a note listing the
-        server-nodeids on the existing leases, so leases on migrated shares
-        can be renewed or cancelled. For immutable shares, IndexError
-        (without the note) will be raised.
+        can be renewed. For immutable shares, IndexError (without the note)
+        will be raised.
         """
         return Any()
 
@@ -176,10 +165,18 @@ class RIStorageServer(RemoteInterface):
                                         tw_vectors=TestAndWriteVectorsForShares,
                                         r_vector=ReadVector,
                                         ):
-        """General-purpose test-and-set operation for mutable slots. Perform
-        a bunch of comparisons against the existing shares. If they all pass,
-        then apply a bunch of write vectors to those shares. Then use the
-        read vectors to extract data from all the shares and return the data.
+        """
+        General-purpose test-read-and-set operation for mutable slots:
+        (1) For submitted shnums, compare the test vectors against extant
+            shares, or against an empty share for shnums that do not exist.
+        (2) Use the read vectors to extract "old data" from extant shares.
+        (3) If all tests in (1) passed, then apply the write vectors
+            (possibly creating new shares).
+        (4) Return whether the tests passed, and the "old data", which does
+            not include any modifications made by the writes.
+
+        The operation does not interleave with other operations on the same
+        shareset.
 
         This method is, um, large. The goal is to allow clients to update all
         the shares associated with a mutable file in a single round trip.
@@ -194,7 +191,9 @@ class RIStorageServer(RemoteInterface):
                              This secret is generated by the client and
                              stored for later comparison by the server. Each
                              server is given a different secret.
-        @param cancel_secret: Like renew_secret, but protects bucket decref.
+        @param cancel_secret: This no longer allows lease cancellation, but
+                              must still be a unique value identifying the
+                              lease. XXX stop relying on it to be unique.
 
         The 'secrets' argument is a tuple of (write_enabler, renew_secret,
         cancel_secret). The first is required to perform any write. The
@@ -204,9 +203,9 @@ class RIStorageServer(RemoteInterface):
         Each share can have a separate test vector (i.e. a list of
         comparisons to perform). If all vectors for all shares pass, then all
         writes for all shares are recorded. Each comparison is a 4-tuple of
-        (offset, length, operator, specimen), which effectively does a bool(
-        (read(offset, length)) OPERATOR specimen ) and only performs the
-        write if all these evaluate to True. Basic test-and-set uses 'eq'.
+        (offset, length, operator, specimen), which effectively does a
+        bool( (read(offset, length)) OPERATOR specimen ) and only performs
+        the write if all these evaluate to True. Basic test-and-set uses 'eq'.
         Write-if-newer uses a seqnum and (offset, length, 'lt', specimen).
         Write-if-same-or-newer uses 'le'.
 
@@ -216,19 +215,46 @@ class RIStorageServer(RemoteInterface):
 
         The write vector will be applied to the given share, expanding it if
         necessary. A write vector applied to a share number that did not
-        exist previously will cause that share to be created.
-
-        Each write vector is accompanied by a 'new_length' argument. If
-        new_length is not None, use it to set the size of the container. This
-        can be used to pre-allocate space for a series of upcoming writes, or
-        truncate existing data. If the container is growing, new_length will
-        be applied before datav. If the container is shrinking, it will be
-        applied afterwards. If new_length==0, the share will be deleted.
+        exist previously will cause that share to be created. Write vectors
+        must not overlap (if they do, this will either cause an error or
+        apply them in an unspecified order). Duplicate write vectors, with
+        the same offset and data, are currently tolerated but are not
+        desirable.
+
+        In Tahoe-LAFS v1.8.3 or later (except 1.9.0a1), if you send a write
+        vector whose offset is beyond the end of the current data, the space
+        between the end of the current data and the beginning of the write
+        vector will be filled with zero bytes. In earlier versions the
+        contents of this space was unspecified (and might end up containing
+        secrets). Storage servers with the new zero-filling behavior will
+        advertise a true value for the 'fills-holes-with-zero-bytes' key
+        (under 'http://allmydata.org/tahoe/protocols/storage/v1') in their
+        version information.
+
+        Each write vector is accompanied by a 'new_length' argument, which
+        can be used to truncate the data. If new_length is not None and it is
+        less than the current size of the data (after applying all write
+        vectors), then the data will be truncated to new_length. If
+        new_length==0, the share will be deleted.
+
+        In Tahoe-LAFS v1.8.2 and earlier, new_length could also be used to
+        enlarge the file by sending a number larger than the size of the data
+        after applying all write vectors. That behavior was not used, and as
+        of Tahoe-LAFS v1.8.3 it no longer works and the new_length is ignored
+        in that case.
+
+        If a storage client knows that the server supports zero-filling, for
+        example from the 'fills-holes-with-zero-bytes' key in its version
+        information, it can extend the file efficiently by writing a single
+        zero byte just before the new end-of-file. Otherwise it must
+        explicitly write zeroes to all bytes between the old and new
+        end-of-file. In any case it should avoid sending new_length larger
+        than the size of the data after applying all write vectors.
 
         The read vector is used to extract data from all known shares,
-        *before* any writes have been applied. The same vector is used for
-        all shares. This captures the state that was tested by the test
-        vector.
+        *before* any writes have been applied. The same read vector is used
+        for all shares. This captures the state that was tested by the test
+        vector, for extant shares.
 
         This method returns two values: a boolean and a dict. The boolean is
         True if the write vectors were applied, False if not. The dict is
@@ -244,7 +270,6 @@ class RIStorageServer(RemoteInterface):
 
         Note that the nodeid here is encoded using the same base32 encoding
         used by Foolscap and allmydata.util.idlib.nodeid_b2a().
-
         """
         return TupleOf(bool, DictOf(int, ReadData))
 
@@ -259,43 +284,44 @@ class RIStorageServer(RemoteInterface):
         (binary) storage index string, and 'shnum' is the integer share
         number. 'reason' is a human-readable explanation of the problem,
         probably including some expected hash values and the computed ones
-        which did not match. Corruption advisories for mutable shares should
+        that did not match. Corruption advisories for mutable shares should
         include a hash of the public key (the same value that appears in the
         mutable-file verify-cap), since the current share format does not
         store that on disk.
         """
 
+
 class IStorageBucketWriter(Interface):
     """
     Objects of this kind live on the client side.
     """
-    def put_block(segmentnum=int, data=ShareData):
-        """@param data: For most segments, this data will be 'blocksize'
-        bytes in length. The last segment might be shorter.
-        @return: a Deferred that fires (with None) when the operation completes
-        """
-
-    def put_plaintext_hashes(hashes=ListOf(Hash)):
+    def put_block(segmentnum, data):
         """
+        @param segmentnum=int
+        @param data=ShareData: For most segments, this data will be 'blocksize'
+        bytes in length. The last segment might be shorter.
         @return: a Deferred that fires (with None) when the operation completes
         """
 
-    def put_crypttext_hashes(hashes=ListOf(Hash)):
+    def put_crypttext_hashes(hashes):
         """
+        @param hashes=ListOf(Hash)
         @return: a Deferred that fires (with None) when the operation completes
         """
 
-    def put_block_hashes(blockhashes=ListOf(Hash)):
+    def put_block_hashes(blockhashes):
         """
+        @param blockhashes=ListOf(Hash)
         @return: a Deferred that fires (with None) when the operation completes
         """
 
-    def put_share_hashes(sharehashes=ListOf(TupleOf(int, Hash))):
+    def put_share_hashes(sharehashes):
         """
+        @param sharehashes=ListOf(TupleOf(int, Hash))
         @return: a Deferred that fires (with None) when the operation completes
         """
 
-    def put_uri_extension(data=URIExtensionData):
+    def put_uri_extension(data):
         """This block of data contains integrity-checking information (hashes
         of plaintext, crypttext, and shares), as well as encoding parameters
         that are necessary to recover the data. This is a serialized dict
@@ -308,6 +334,7 @@ class IStorageBucketWriter(Interface):
             assert re.match(r'^[a-zA-Z_\-]+$', k)
             write(k + ':' + netstring(dict[k]))
 
+        @param data=URIExtensionData
         @return: a Deferred that fires (with None) when the operation completes
         """
 
@@ -320,12 +347,15 @@ class IStorageBucketWriter(Interface):
         @return: a Deferred that fires (with None) when the operation completes
         """
 
-class IStorageBucketReader(Interface):
 
-    def get_block_data(blocknum=int, blocksize=int, size=int):
+class IStorageBucketReader(Interface):
+    def get_block_data(blocknum, blocksize, size):
         """Most blocks will be the same size. The last block might be shorter
         than the others.
 
+        @param blocknum=int
+        @param blocksize=int
+        @param size=int
         @return: ShareData
         """
 
@@ -334,12 +364,13 @@ class IStorageBucketReader(Interface):
         @return: ListOf(Hash)
         """
 
-    def get_block_hashes(at_least_these=SetOf(int)):
+    def get_block_hashes(at_least_these=()):
         """
+        @param at_least_these=SetOf(int)
         @return: ListOf(Hash)
         """
 
-    def get_share_hashes(at_least_these=SetOf(int)):
+    def get_share_hashes():
         """
         @return: ListOf(TupleOf(int, Hash))
         """
@@ -349,14 +380,19 @@ class IStorageBucketReader(Interface):
         @return: URIExtensionData
         """
 
+
 class IStorageBroker(Interface):
-    def get_servers_for_index(peer_selection_index):
+    def get_servers_for_psi(peer_selection_index):
+        """
+        @return: list of IServer instances
         """
-        @return: list of (peerid, versioned-rref) tuples
+    def get_connected_servers():
         """
-    def get_all_servers():
+        @return: frozenset of connected IServer instances
         """
-        @return: frozenset of (peerid, versioned-rref) tuples
+    def get_known_servers():
+        """
+        @return: frozenset of IServer instances
         """
     def get_all_serverids():
         """
@@ -392,7 +428,7 @@ class IStorageBroker(Interface):
           remote_host: the IAddress, if connected, otherwise None
 
         This method is intended for monitoring interfaces, such as a web page
-        which describes connecting and connected peers.
+        that describes connecting and connected peers.
         """
 
     def get_all_peerids():
@@ -411,6 +447,99 @@ class IStorageBroker(Interface):
         """
 
 
+class IDisplayableServer(Interface):
+    def get_nickname():
+        pass
+
+    def get_name():
+        pass
+
+    def get_longname():
+        pass
+
+
+class IServer(IDisplayableServer):
+    """I live in the client, and represent a single server."""
+    def start_connecting(tub, trigger_cb):
+        pass
+
+    def get_rref():
+        """Once a server is connected, I return a RemoteReference.
+        Before a server is connected for the first time, I return None.
+
+        Note that the rref I return will start producing DeadReferenceErrors
+        once the connection is lost.
+        """
+
+
+class IMutableSlotWriter(Interface):
+    """
+    The interface for a writer around a mutable slot on a remote server.
+    """
+    def set_checkstring(seqnum_or_checkstring, root_hash=None, salt=None):
+        """
+        Set the checkstring that I will pass to the remote server when
+        writing.
+
+            @param checkstring A packed checkstring to use.
+
+        Note that implementations can differ in which semantics they
+        wish to support for set_checkstring -- they can, for example,
+        build the checkstring themselves from its constituents, or
+        some other thing.
+        """
+
+    def get_checkstring():
+        """
+        Get the checkstring that I think currently exists on the remote
+        server.
+        """
+
+    def put_block(data, segnum, salt):
+        """
+        Add a block and salt to the share.
+        """
+
+    def put_encprivkey(encprivkey):
+        """
+        Add the encrypted private key to the share.
+        """
+
+    def put_blockhashes(blockhashes):
+        """
+        @param blockhashes=list
+        Add the block hash tree to the share.
+        """
+
+    def put_sharehashes(sharehashes):
+        """
+        @param sharehashes=dict
+        Add the share hash chain to the share.
+        """
+
+    def get_signable():
+        """
+        Return the part of the share that needs to be signed.
+        """
+
+    def put_signature(signature):
+        """
+        Add the signature to the share.
+        """
+
+    def put_verification_key(verification_key):
+        """
+        Add the verification key to the share.
+        """
+
+    def finish_publishing():
+        """
+        Do anything necessary to finish writing the share to a remote
+        server. I require that no further publishing needs to take place
+        after this method has been called.
+        """
+
+
 class IURI(Interface):
     def init_from_string(uri):
         """Accept a string (as created by my to_string() method) and populate
@@ -426,8 +555,9 @@ class IURI(Interface):
         """Return True if the data can be modified by *somebody* (perhaps
         someone who has a more powerful URI than this one)."""
 
+    # TODO: rename to get_read_cap()
     def get_readonly():
-        """Return another IURI instance, which represents a read-only form of
+        """Return another IURI instance that represents a read-only form of
         this one. If is_readonly() is True, this returns self."""
 
     def get_verify_cap():
@@ -442,6 +572,7 @@ class IURI(Interface):
         """Return a string of printable ASCII characters, suitable for
         passing into init_from_string."""
 
+
 class IVerifierURI(Interface, IURI):
     def init_from_string(uri):
         """Accept a string (as created by my to_string() method) and populate
@@ -453,54 +584,235 @@ class IVerifierURI(Interface, IURI):
         """Return a string of printable ASCII characters, suitable for
         passing into init_from_string."""
 
+
 class IDirnodeURI(Interface):
-    """I am a URI which represents a dirnode."""
+    """I am a URI that represents a dirnode."""
 
 
 class IFileURI(Interface):
-    """I am a URI which represents a filenode."""
+    """I am a URI that represents a filenode."""
     def get_size():
         """Return the length (in bytes) of the file that I represent."""
 
+
 class IImmutableFileURI(IFileURI):
     pass
 
 class IMutableFileURI(Interface):
-    """I am a URI which represents a mutable filenode."""
+    pass
+
 class IDirectoryURI(Interface):
     pass
+
 class IReadonlyDirectoryURI(Interface):
     pass
 
-class CannotPackUnknownNodeError(Exception):
-    """UnknownNodes (using filecaps from the future that we don't understand)
-    cannot yet be copied safely, so I refuse to copy them."""
 
-class UnhandledCapTypeError(Exception):
-    """I recognize the cap/URI, but I cannot create an IFilesystemNode for
-    it."""
+class CapConstraintError(Exception):
+    """A constraint on a cap was violated."""
 
-class IFilesystemNode(Interface):
-    def get_uri():
+class MustBeDeepImmutableError(CapConstraintError):
+    """Mutable children cannot be added to an immutable directory.
+    Also, caps obtained from an immutable directory can trigger this error
+    if they are later found to refer to a mutable object and then used."""
+
+class MustBeReadonlyError(CapConstraintError):
+    """Known write caps cannot be specified in a ro_uri field. Also,
+    caps obtained from a ro_uri field can trigger this error if they
+    are later found to be write caps and then used."""
+
+class MustNotBeUnknownRWError(CapConstraintError):
+    """Cannot add an unknown child cap specified in a rw_uri field."""
+
+
+class IReadable(Interface):
+    """I represent a readable object -- either an immutable file, or a
+    specific version of a mutable file.
+    """
+
+    def is_readonly():
+        """Return True if this reference provides mutable access to the given
+        file or directory (i.e. if you can modify it), or False if not. Note
+        that even if this reference is read-only, someone else may hold a
+        read-write reference to it.
+
+        For an IReadable returned by get_best_readable_version(), this will
+        always return True, but for instances of subinterfaces such as
+        IMutableFileVersion, it may return False."""
+
+    def is_mutable():
+        """Return True if this file or directory is mutable (by *somebody*,
+        not necessarily you), False if it is is immutable. Note that a file
+        might be mutable overall, but your reference to it might be
+        read-only. On the other hand, all references to an immutable file
+        will be read-only; there are no read-write references to an immutable
+        file."""
+
+    def get_storage_index():
+        """Return the storage index of the file."""
+
+    def get_size():
+        """Return the length (in bytes) of this readable object."""
+
+    def download_to_data():
+        """Download all of the file contents. I return a Deferred that fires
+        with the contents as a byte string."""
+
+    def read(consumer, offset=0, size=None):
+        """Download a portion (possibly all) of the file's contents, making
+        them available to the given IConsumer. Return a Deferred that fires
+        (with the consumer) when the consumer is unregistered (either because
+        the last byte has been given to it, or because the consumer threw an
+        exception during write(), possibly because it no longer wants to
+        receive data). The portion downloaded will start at 'offset' and
+        contain 'size' bytes (or the remainder of the file if size==None). It
+        is an error to read beyond the end of the file: callers must use
+        get_size() and clip any non-default offset= and size= parameters. It
+        is permissible to read zero bytes.
+
+        The consumer will be used in non-streaming mode: an IPullProducer
+        will be attached to it.
+
+        The consumer will not receive data right away: several network trips
+        must occur first. The order of events will be::
+
+         consumer.registerProducer(p, streaming)
+          (if streaming == False)::
+           consumer does p.resumeProducing()
+            consumer.write(data)
+           consumer does p.resumeProducing()
+            consumer.write(data).. (repeat until all data is written)
+         consumer.unregisterProducer()
+         deferred.callback(consumer)
+
+        If a download error occurs, or an exception is raised by
+        consumer.registerProducer() or consumer.write(), I will call
+        consumer.unregisterProducer() and then deliver the exception via
+        deferred.errback(). To cancel the download, the consumer should call
+        p.stopProducing(), which will result in an exception being delivered
+        via deferred.errback().
+
+        See src/allmydata/util/consumer.py for an example of a simple
+        download-to-memory consumer.
         """
-        Return the URI string that can be used by others to get access to
-        this node. If this node is read-only, the URI will only offer
-        read-only access. If this node is read-write, the URI will offer
-        read-write access.
 
-        If you have read-write access to a node and wish to share merely
-        read-only access with others, use get_readonly_uri().
+
+class IWriteable(Interface):
+    """
+    I define methods that callers can use to update SDMF and MDMF
+    mutable files on a Tahoe-LAFS grid.
+    """
+    # XXX: For the moment, we have only this. It is possible that we
+    #      want to move overwrite() and modify() in here too.
+    def update(data, offset):
+        """
+        I write the data from my data argument to the MDMF file,
+        starting at offset. I continue writing data until my data
+        argument is exhausted, appending data to the file as necessary.
+        """
+        # assert IMutableUploadable.providedBy(data)
+        # to append data: offset=node.get_size_of_best_version()
+        # do we want to support compacting MDMF?
+        # for an MDMF file, this can be done with O(data.get_size())
+        # memory. For an SDMF file, any modification takes
+        # O(node.get_size_of_best_version()).
+
+
+class IMutableFileVersion(IReadable):
+    """I provide access to a particular version of a mutable file. The
+    access is read/write if I was obtained from a filenode derived from
+    a write cap, or read-only if the filenode was derived from a read cap.
+    """
+
+    def get_sequence_number():
+        """Return the sequence number of this version."""
+
+    def get_servermap():
+        """Return the IMutableFileServerMap instance that was used to create
+        this object.
         """
 
-    def get_readonly_uri():
-        """Return the URI string that can be used by others to get read-only
-        access to this node. The result is a read-only URI, regardless of
-        whether this node is read-only or read-write.
+    def get_writekey():
+        """Return this filenode's writekey, or None if the node does not have
+        write-capability. This may be used to assist with data structures
+        that need to make certain data available only to writers, such as the
+        read-write child caps in dirnodes. The recommended process is to have
+        reader-visible data be submitted to the filenode in the clear (where
+        it will be encrypted by the filenode using the readkey), but encrypt
+        writer-visible data using this writekey.
+        """
 
-        If you have merely read-only access to this node, get_readonly_uri()
-        will return the same thing as get_uri().
+    def overwrite(new_contents):
+        """Replace the contents of the mutable file, provided that no other
+        node has published (or is attempting to publish, concurrently) a
+        newer version of the file than this one.
+
+        I will avoid modifying any share that is different than the version
+        given by get_sequence_number(). However, if another node is writing
+        to the file at the same time as me, I may manage to update some shares
+        while they update others. If I see any evidence of this, I will signal
+        UncoordinatedWriteError, and the file will be left in an inconsistent
+        state (possibly the version you provided, possibly the old version,
+        possibly somebody else's version, and possibly a mix of shares from
+        all of these).
+
+        The recommended response to UncoordinatedWriteError is to either
+        return it to the caller (since they failed to coordinate their
+        writes), or to attempt some sort of recovery. It may be sufficient to
+        wait a random interval (with exponential backoff) and repeat your
+        operation. If I do not signal UncoordinatedWriteError, then I was
+        able to write the new version without incident.
+
+        I return a Deferred that fires (with a PublishStatus object) when the
+        update has completed.
         """
 
+    def modify(modifier_cb):
+        """Modify the contents of the file, by downloading this version,
+        applying the modifier function (or bound method), then uploading
+        the new version. This will succeed as long as no other node
+        publishes a version between the download and the upload.
+        I return a Deferred that fires (with a PublishStatus object) when
+        the update is complete.
+
+        The modifier callable will be given three arguments: a string (with
+        the old contents), a 'first_time' boolean, and a servermap. As with
+        download_to_data(), the old contents will be from this version,
+        but the modifier can use the servermap to make other decisions
+        (such as refusing to apply the delta if there are multiple parallel
+        versions, or if there is evidence of a newer unrecoverable version).
+        'first_time' will be True the first time the modifier is called,
+        and False on any subsequent calls.
+
+        The callable should return a string with the new contents. The
+        callable must be prepared to be called multiple times, and must
+        examine the input string to see if the change that it wants to make
+        is already present in the old version. If it does not need to make
+        any changes, it can either return None, or return its input string.
+
+        If the modifier raises an exception, it will be returned in the
+        errback.
+        """
+
+
+# The hierarchy looks like this:
+#  IFilesystemNode
+#   IFileNode
+#    IMutableFileNode
+#    IImmutableFileNode
+#   IDirectoryNode
+
+class IFilesystemNode(Interface):
+    def get_cap():
+        """Return the strongest 'cap instance' associated with this node.
+        (writecap for writeable-mutable files/directories, readcap for
+        immutable or readonly-mutable files/directories). To convert this
+        into a string, call .to_string() on the result."""
+
+    def get_readcap():
+        """Return a readonly cap instance for this node. For immutable or
+        readonly nodes, get_cap() and get_readcap() return the same thing."""
+
     def get_repair_cap():
         """Return an IURI instance that can be used to repair the file, or
         None if this node cannot be repaired (either because it is not
@@ -517,10 +829,34 @@ class IFilesystemNode(Interface):
         it holds a share for the file or directory.
         """
 
+    def get_uri():
+        """Return the URI string corresponding to the strongest cap associated
+        with this node. If this node is read-only, the URI will only offer
+        read-only access. If this node is read-write, the URI will offer
+        read-write access.
+
+        If you have read-write access to a node and wish to share merely
+        read-only access with others, use get_readonly_uri().
+        """
+
+    def get_write_uri():
+        """Return the URI string that can be used by others to get write
+        access to this node, if it is writeable. If this is a read-only node,
+        return None."""
+
+    def get_readonly_uri():
+        """Return the URI string that can be used by others to get read-only
+        access to this node. The result is a read-only URI, regardless of
+        whether this node is read-only or read-write.
+
+        If you have merely read-only access to this node, get_readonly_uri()
+        will return the same thing as get_uri().
+        """
+
     def get_storage_index():
         """Return a string with the (binary) storage index in use on this
         download. This may be None if there is no storage index (i.e. LIT
-        files)."""
+        files and directories)."""
 
     def is_readonly():
         """Return True if this reference provides mutable access to the given
@@ -537,73 +873,76 @@ class IFilesystemNode(Interface):
         file.
         """
 
-class IMutableFilesystemNode(IFilesystemNode):
-    pass
+    def is_unknown():
+        """Return True if this is an unknown node."""
 
-class IFileNode(IFilesystemNode):
-    def download(target):
-        """Download the file's contents to a given IDownloadTarget"""
+    def is_allowed_in_immutable_directory():
+        """Return True if this node is allowed as a child of a deep-immutable
+        directory. This is true if either the node is of a known-immutable type,
+        or it is unknown and read-only.
+        """
 
-    def download_to_data():
-        """Download the file's contents. Return a Deferred that fires
-        with those contents."""
+    def raise_error():
+        """Raise any error associated with this node."""
 
+    # XXX: These may not be appropriate outside the context of an IReadable.
     def get_size():
-        """Return the length (in bytes) of the data this node represents."""
+        """Return the length (in bytes) of the data this node represents. For
+        directory nodes, I return the size of the backing store. I return
+        synchronously and do not consult the network, so for mutable objects,
+        I will return the most recently observed size for the object, or None
+        if I don't remember a size. Use get_current_size, which returns a
+        Deferred, if you want more up-to-date information."""
 
-    def read(consumer, offset=0, size=None):
-        """Download a portion (possibly all) of the file's contents, making
-        them available to the given IConsumer. Return a Deferred that fires
-        (with the consumer) when the consumer is unregistered (either because
-        the last byte has been given to it, or because the consumer threw an
-        exception during write(), possibly because it no longer wants to
-        receive data). The portion downloaded will start at 'offset' and
-        contain 'size' bytes (or the remainder of the file if size==None).
+    def get_current_size():
+        """I return a Deferred that fires with the length (in bytes) of the
+        data this node represents.
+        """
 
-        The consumer will be used in non-streaming mode: an IPullProducer
-        will be attached to it.
 
-        The consumer will not receive data right away: several network trips
-        must occur first. The order of events will be::
+class IFileNode(IFilesystemNode):
+    """I am a node that represents a file: a sequence of bytes. I am not a
+    container, like IDirectoryNode."""
+    def get_best_readable_version():
+        """Return a Deferred that fires with an IReadable for the 'best'
+        available version of the file. The IReadable provides only read
+        access, even if this filenode was derived from a write cap.
 
-         consumer.registerProducer(p, streaming)
-          (if streaming == False)::
-           consumer does p.resumeProducing()
-            consumer.write(data)
-           consumer does p.resumeProducing()
-            consumer.write(data).. (repeat until all data is written)
-         consumer.unregisterProducer()
-         deferred.callback(consumer)
+        For an immutable file, there is only one version. For a mutable
+        file, the 'best' version is the recoverable version with the
+        highest sequence number. If no uncoordinated writes have occurred,
+        and if enough shares are available, then this will be the most
+        recent version that has been uploaded. If no version is recoverable,
+        the Deferred will errback with an UnrecoverableFileError.
+        """
 
-        If a download error occurs, or an exception is raised by
-        consumer.registerProducer() or consumer.write(), I will call
-        consumer.unregisterProducer() and then deliver the exception via
-        deferred.errback(). To cancel the download, the consumer should call
-        p.stopProducing(), which will result in an exception being delivered
-        via deferred.errback().
+    def download_best_version():
+        """Download the contents of the version that would be returned
+        by get_best_readable_version(). This is equivalent to calling
+        download_to_data() on the IReadable given by that method.
 
-        A simple download-to-memory consumer example would look like this::
-
-         class MemoryConsumer:
-           implements(IConsumer)
-           def __init__(self):
-             self.chunks = []
-             self.done = False
-           def registerProducer(self, p, streaming):
-             assert streaming == False
-             while not self.done:
-               p.resumeProducing()
-           def write(self, data):
-             self.chunks.append(data)
-           def unregisterProducer(self):
-             self.done = True
-         d = filenode.read(MemoryConsumer())
-         d.addCallback(lambda mc: "".join(mc.chunks))
-         return d
+        I return a Deferred that fires with a byte string when the file
+        has been fully downloaded. To support streaming download, use
+        the 'read' method of IReadable. If no version is recoverable,
+        the Deferred will errback with an UnrecoverableFileError.
+        """
 
+    def get_size_of_best_version():
+        """Find the size of the version that would be returned by
+        get_best_readable_version().
+
+        I return a Deferred that fires with an integer. If no version
+        is recoverable, the Deferred will errback with an
+        UnrecoverableFileError.
         """
 
-class IMutableFileNode(IFileNode, IMutableFilesystemNode):
+
+class IImmutableFileNode(IFileNode, IReadable):
+    """I am a node representing an immutable file. Immutable files have
+    only one version"""
+
+
+class IMutableFileNode(IFileNode):
     """I provide access to a 'mutable file', which retains its identity
     regardless of what contents are put in it.
 
@@ -611,7 +950,7 @@ class IMutableFileNode(IFileNode, IMutableFilesystemNode):
     multiple versions of a file present in the grid, some of which might be
     unrecoverable (i.e. have fewer than 'k' shares). These versions are
     loosely ordered: each has a sequence number and a hash, and any version
-    with seqnum=N was uploaded by a node which has seen at least one version
+    with seqnum=N was uploaded by a node that has seen at least one version
     with seqnum=N-1.
 
     The 'servermap' (an instance of IMutableFileServerMap) is used to
@@ -662,26 +1001,16 @@ class IMutableFileNode(IFileNode, IMutableFilesystemNode):
     only be retrieved and updated all-at-once, as a single big string. Future
     versions of our mutable files will remove this restriction.
     """
-
-    def download_best_version():
-        """Download the 'best' available version of the file, meaning one of
-        the recoverable versions with the highest sequence number. If no
+    def get_best_mutable_version():
+        """Return a Deferred that fires with an IMutableFileVersion for
+        the 'best' available version of the file. The best version is
+        the recoverable version with the highest sequence number. If no
         uncoordinated writes have occurred, and if enough shares are
-        available, then this will be the most recent version that has been
-        uploaded.
+        available, then this will be the most recent version that has
+        been uploaded.
 
-        I update an internal servermap with MODE_READ, determine which
-        version of the file is indicated by
-        servermap.best_recoverable_version(), and return a Deferred that
-        fires with its contents. If no version is recoverable, the Deferred
-        will errback with UnrecoverableFileError.
-        """
-
-    def get_size_of_best_version():
-        """Find the size of the version that would be downloaded with
-        download_best_version(), without actually downloading the whole file.
-
-        I return a Deferred that fires with an integer.
+        If no version is recoverable, the Deferred will errback with an
+        UnrecoverableFileError.
         """
 
     def overwrite(new_contents):
@@ -720,7 +1049,6 @@ class IMutableFileNode(IFileNode, IMutableFilesystemNode):
         errback.
         """
 
-
     def get_servermap(mode):
         """Return a Deferred that fires with an IMutableFileServerMap
         instance, updated using the given mode.
@@ -731,7 +1059,7 @@ class IMutableFileNode(IFileNode, IMutableFilesystemNode):
         as a guide to where the shares are located.
 
         I return a Deferred that fires with the requested contents, or
-        errbacks with UnrecoverableFileError. Note that a servermap which was
+        errbacks with UnrecoverableFileError. Note that a servermap that was
         updated with MODE_ANYTHING or MODE_READ may not know about shares for
         all versions (those modes stop querying servers as soon as they can
         fulfil their goals), so you may want to use MODE_CHECK (which checks
@@ -774,15 +1102,24 @@ class IMutableFileNode(IFileNode, IMutableFilesystemNode):
         writer-visible data using this writekey.
         """
 
+    def get_version():
+        """Returns the mutable file protocol version."""
+
+
 class NotEnoughSharesError(Exception):
-    """Download was unable to get enough shares, or upload was unable to
-    place 'shares_of_happiness' shares."""
+    """Download was unable to get enough shares"""
 
 class NoSharesError(Exception):
-    """Upload or Download was unable to get any shares at all."""
+    """Download was unable to get any shares at all."""
+
+class DownloadStopped(Exception):
+    pass
+
+class UploadUnhappinessError(Exception):
+    """Upload was unable to satisfy 'servers_of_happiness'"""
 
 class UnableToFetchCriticalDownloadDataError(Exception):
-    """I was unable to fetch some piece of critical data which is supposed to
+    """I was unable to fetch some piece of critical data that is supposed to
     be identically present in all shares."""
 
 class NoServersError(Exception):
@@ -794,12 +1131,20 @@ class ExistingChildError(Exception):
     exists, and overwrite= was set to False."""
 
 class NoSuchChildError(Exception):
-    """A directory node was asked to fetch a child which does not exist."""
+    """A directory node was asked to fetch a child that does not exist."""
+    def __str__(self):
+        # avoid UnicodeEncodeErrors when converting to str
+        return self.__repr__()
+
+class ChildOfWrongTypeError(Exception):
+    """An operation was attempted on a child of the wrong type (file or directory)."""
 
-class IDirectoryNode(IMutableFilesystemNode):
-    """I represent a name-to-child mapping, holding the tahoe equivalent of a
-    directory. All child names are unicode strings, and all children are some
-    sort of IFilesystemNode (either files or subdirectories).
+
+class IDirectoryNode(IFilesystemNode):
+    """I represent a filesystem node that is a container, with a
+    name-to-child mapping, holding the tahoe equivalent of a directory. All
+    child names are unicode strings, and all children are some sort of
+    IFilesystemNode (a file, subdirectory, or unknown node).
     """
 
     def get_uri():
@@ -823,8 +1168,8 @@ class IDirectoryNode(IMutableFilesystemNode):
     def list():
         """I return a Deferred that fires with a dictionary mapping child
         name (a unicode string) to (node, metadata_dict) tuples, in which
-        'node' is either an IFileNode or IDirectoryNode, and 'metadata_dict'
-        is a dictionary of metadata."""
+        'node' is an IFilesystemNode and 'metadata_dict' is a dictionary of
+        metadata."""
 
     def has_child(name):
         """I return a Deferred that fires with a boolean, True if there
@@ -833,28 +1178,26 @@ class IDirectoryNode(IMutableFilesystemNode):
 
     def get(name):
         """I return a Deferred that fires with a specific named child node,
-        either an IFileNode or an IDirectoryNode. The child name must be a
-        unicode string. I raise NoSuchChildError if I do not have a child by
-        that name."""
+        which is an IFilesystemNode. The child name must be a unicode string.
+        I raise NoSuchChildError if I do not have a child by that name."""
 
     def get_metadata_for(name):
-        """I return a Deferred that fires with the metadata dictionary for a
-        specific named child node. This metadata is stored in the *edge*, not
-        in the child, so it is attached to the parent dirnode rather than the
-        child dir-or-file-node. The child name must be a unicode string. I
-        raise NoSuchChildError if I do not have a child by that name."""
+        """I return a Deferred that fires with the metadata dictionary for
+        a specific named child node. The child name must be a unicode string.
+        This metadata is stored in the *edge*, not in the child, so it is
+        attached to the parent dirnode rather than the child node.
+        raise NoSuchChildError if I do not have a child by that name."""
 
     def set_metadata_for(name, metadata):
         """I replace any existing metadata for the named child with the new
         metadata. The child name must be a unicode string. This metadata is
         stored in the *edge*, not in the child, so it is attached to the
-        parent dirnode rather than the child dir-or-file-node. I return a
-        Deferred (that fires with this dirnode) when the operation is
-        complete. I raise NoSuchChildError if I do not have a child by that
-        name."""
+        parent dirnode rather than the child node. I return a Deferred
+        (that fires with this dirnode) when the operation is complete.
+        I raise NoSuchChildError if I do not have a child by that name."""
 
     def get_child_at_path(path):
-        """Transform a child path into an IDirectoryNode or IFileNode.
+        """Transform a child path into an IFilesystemNode.
 
         I perform a recursive series of 'get' operations to find the named
         descendant node. I return a Deferred that fires with the node, or
@@ -865,8 +1208,7 @@ class IDirectoryNode(IMutableFilesystemNode):
         """
 
     def get_child_and_metadata_at_path(path):
-        """Transform a child path into an IDirectoryNode/IFileNode and
-        metadata.
+        """Transform a child path into an IFilesystemNode and metadata.
 
         I am like get_child_at_path(), but my Deferred fires with a tuple of
         (node, metadata). The metadata comes from the last edge. If the path
@@ -880,10 +1222,12 @@ class IDirectoryNode(IMutableFilesystemNode):
         an existing child will cause me to return ExistingChildError. The
         child name must be a unicode string.
 
-        The child caps could be for a file, or for a directory. If the new
-        child is read/write, you will provide both writecap and readcap. If
-        the child is read-only, you will provide the readcap write (i.e. the
-        writecap= and readcap= arguments will both be the child's readcap).
+        The child caps could be for a file, or for a directory. If you have
+        both the writecap and readcap, you should provide both arguments.
+        If you have only one cap and don't know whether it is read-only,
+        provide it as the writecap argument and leave the readcap as None.
+        If you have only one cap that is known to be read-only, provide it
+        as the readcap argument and leave the writecap as None.
         The filecaps are typically obtained from an IFilesystemNode with
         get_uri() and get_readonly_uri().
 
@@ -892,18 +1236,19 @@ class IDirectoryNode(IMutableFilesystemNode):
         as the default value of None, I will set ['mtime'] to the current
         time, and I will set ['ctime'] to the current time if there was not
         already a child by this name present. This roughly matches the
-        ctime/mtime semantics of traditional filesystems.
+        ctime/mtime semantics of traditional filesystems.  See the
+        "About the metadata" section of webapi.txt for futher information.
 
         If this directory node is read-only, the Deferred will errback with a
-        NotMutableError."""
+        NotWriteableError."""
 
     def set_children(entries, overwrite=True):
         """Add multiple children (by writecap+readcap) to a directory node.
         Takes a dictionary, with childname as keys and (writecap, readcap)
         tuples (or (writecap, readcap, metadata) triples) as values. Returns
-        a Deferred that fires (with None) when the operation finishes. This
-        is equivalent to calling set_uri() multiple times, but is much more
-        efficient. All child names must be unicode strings.
+        a Deferred that fires (with this dirnode) when the operation
+        finishes. This is equivalent to calling set_uri() multiple times, but
+        is much more efficient. All child names must be unicode strings.
         """
 
     def set_node(name, child, metadata=None, overwrite=True):
@@ -911,45 +1256,53 @@ class IDirectoryNode(IMutableFilesystemNode):
         when the operation finishes. This Deferred will fire with the child
         node that was just added. I will replace any existing child of the
         same name. The child name must be a unicode string. The 'child'
-        instance must be an instance providing IDirectoryNode or IFileNode.
+        instance must be an instance providing IFilesystemNode.
 
         If metadata= is provided, I will use it as the metadata for the named
         edge. This will replace any existing metadata. If metadata= is left
         as the default value of None, I will set ['mtime'] to the current
         time, and I will set ['ctime'] to the current time if there was not
         already a child by this name present. This roughly matches the
-        ctime/mtime semantics of traditional filesystems.
+        ctime/mtime semantics of traditional filesystems. See the
+        "About the metadata" section of webapi.txt for futher information.
 
         If this directory node is read-only, the Deferred will errback with a
-        NotMutableError."""
+        NotWriteableError."""
 
     def set_nodes(entries, overwrite=True):
-        """Add multiple (name, child_node) pairs (or (name, child_node,
-        metadata) triples) to a directory node. Returns a Deferred that fires
-        (with None) when the operation finishes. This is equivalent to
-        calling set_node() multiple times, but is much more efficient. All
-        child names must be unicode strings."""
-
+        """Add multiple children to a directory node. Takes a dict mapping
+        unicode childname to (child_node, metdata) tuples. If metdata=None,
+        the original metadata is left unmodified. Returns a Deferred that
+        fires (with this dirnode) when the operation finishes. This is
+        equivalent to calling set_node() multiple times, but is much more
+        efficient."""
 
     def add_file(name, uploadable, metadata=None, overwrite=True):
         """I upload a file (using the given IUploadable), then attach the
-        resulting FileNode to the directory at the given name. I set metadata
-        the same way as set_uri and set_node. The child name must be a
-        unicode string.
+        resulting ImmutableFileNode to the directory at the given name. I set
+        metadata the same way as set_uri and set_node. The child name must be
+        unicode string.
 
         I return a Deferred that fires (with the IFileNode of the uploaded
         file) when the operation completes."""
 
-    def delete(name):
+    def delete(name, must_exist=True, must_be_directory=False, must_be_file=False):
         """I remove the child at the specific name. I return a Deferred that
         fires when the operation finishes. The child name must be a unicode
-        string. I raise NoSuchChildError if I do not have a child by that
-        name."""
-
-    def create_empty_directory(name, overwrite=True):
-        """I create and attach an empty directory at the given name. The
-        child name must be a unicode string. I return a Deferred that fires
-        when the operation finishes."""
+        string. If must_exist is True and I do not have a child by that name,
+        I raise NoSuchChildError. If must_be_directory is True and the child
+        is a file, or if must_be_file is True and the child is a directory,
+        I raise ChildOfWrongTypeError."""
+
+    def create_subdirectory(name, initial_children={}, overwrite=True,
+                            mutable=True, mutable_version=None, metadata=None):
+        """I create and attach a directory at the given name. The new
+        directory can be empty, or it can be populated with children
+        according to 'initial_children', which takes a dictionary in the same
+        format as set_nodes (i.e. mapping unicode child name to (childnode,
+        metadata) tuples). The child name must be a unicode string. I return
+        a Deferred that fires (with the new directory node) when the
+        operation finishes."""
 
     def move_child_to(current_child_name, new_parent, new_child_name=None,
                       overwrite=True):
@@ -1021,6 +1374,7 @@ class IDirectoryNode(IMutableFilesystemNode):
         takes several minutes of 100% CPU for ~1700 directories).
         """
 
+
 class ICodecEncoder(Interface):
     def set_params(data_size, required_shares, max_shares):
         """Set up the parameters of this encoder.
@@ -1101,7 +1455,7 @@ class ICodecEncoder(Interface):
         if you initially thought you were going to use 10 peers, started
         encoding, and then two of the peers dropped out: you could use
         desired_share_ids= to skip the work (both memory and CPU) of
-        producing shares for the peers which are no longer available.
+        producing shares for the peers that are no longer available.
 
         """
 
@@ -1118,20 +1472,56 @@ class ICodecEncoder(Interface):
         encode(), unless of course it already happens to be an even multiple
         of required_shares in length.)
 
-         ALSO: the requirement to break up your data into 'required_shares'
-         chunks before calling encode() feels a bit surprising, at least from
-         the point of view of a user who doesn't know how FEC works. It feels
-         like an implementation detail that has leaked outside the
-         abstraction barrier. Can you imagine a use case in which the data to
-         be encoded might already be available in pre-segmented chunks, such
-         that it is faster or less work to make encode() take a list rather
-         than splitting a single string?
-
-         ALSO ALSO: I think 'inshares' is a misleading term, since encode()
-         is supposed to *produce* shares, so what it *accepts* should be
-         something other than shares. Other places in this interface use the
-         word 'data' for that-which-is-not-shares.. maybe we should use that
-         term?
+        Note: the requirement to break up your data into
+        'required_shares' chunks of exactly the right length before
+        calling encode() is surprising from point of view of a user
+        who doesn't know how FEC works. It feels like an
+        implementation detail that has leaked outside the abstraction
+        barrier. Is there a use case in which the data to be encoded
+        might already be available in pre-segmented chunks, such that
+        it is faster or less work to make encode() take a list rather
+        than splitting a single string?
+
+        Yes, there is: suppose you are uploading a file with K=64,
+        N=128, segsize=262,144. Then each in-share will be of size
+        4096. If you use this .encode() API then your code could first
+        read each successive 4096-byte chunk from the file and store
+        each one in a Python string and store each such Python string
+        in a Python list. Then you could call .encode(), passing that
+        list as "inshares". The encoder would generate the other 64
+        "secondary shares" and return to you a new list containing
+        references to the same 64 Python strings that you passed in
+        (as the primary shares) plus references to the new 64 Python
+        strings.
+
+        (You could even imagine that your code could use readv() so
+        that the operating system can arrange to get all of those
+        bytes copied from the file into the Python list of Python
+        strings as efficiently as possible instead of having a loop
+        written in C or in Python to copy the next part of the file
+        into the next string.)
+
+        On the other hand if you instead use the .encode_proposal()
+        API (above), then your code can first read in all of the
+        262,144 bytes of the segment from the file into a Python
+        string, then call .encode_proposal() passing the segment data
+        as the "data" argument. The encoder would basically first
+        split the "data" argument into a list of 64 in-shares of 4096
+        byte each, and then do the same thing that .encode() does. So
+        this would result in a little bit more copying of data and a
+        little bit higher of a "maximum memory usage" during the
+        process, although it might or might not make a practical
+        difference for our current use cases.
+
+        Note that "inshares" is a strange name for the parameter if
+        you think of the parameter as being just for feeding in data
+        to the codec. It makes more sense if you think of the result
+        of this encoding as being the set of shares from inshares plus
+        an extra set of "secondary shares" (or "check shares"). It is
+        a surprising name! If the API is going to be surprising then
+        the name should be surprising. If we switch to
+        encode_proposal() above then we should also switch to an
+        unsurprising name.
 
         'desired_share_ids', if provided, is required to be a sequence of
         ints, each of which is required to be >= 0 and < max_shares. If not
@@ -1140,7 +1530,7 @@ class ICodecEncoder(Interface):
         if you initially thought you were going to use 10 peers, started
         encoding, and then two of the peers dropped out: you could use
         desired_share_ids= to skip the work (both memory and CPU) of
-        producing shares for the peers which are no longer available.
+        producing shares for the peers that are no longer available.
 
         For each call, encode() will return a Deferred that fires with two
         lists, one containing shares and the other containing the shareids.
@@ -1197,7 +1587,7 @@ class ICodecDecoder(Interface):
         required to be of the same length.  The i'th element of their_shareids
         is required to be the shareid of the i'th buffer in some_shares.
 
-        This returns a Deferred which fires with a sequence of buffers. This
+        This returns a Deferred that fires with a sequence of buffers. This
         sequence will contain all of the segments of the original data, in
         order. The sum of the lengths of all of the buffers will be the
         'data_size' value passed into the original ICodecEncode.set_params()
@@ -1217,6 +1607,7 @@ class ICodecDecoder(Interface):
         call.
         """
 
+
 class IEncoder(Interface):
     """I take an object that provides IEncryptedUploadable, which provides
     encrypted data, and a list of shareholders. I then encode, hash, and
@@ -1235,21 +1626,6 @@ class IEncoder(Interface):
         """Specify the number of bytes that will be encoded. This must be
         peformed before get_serialized_params() can be called.
         """
-    def set_params(params):
-        """Override the default encoding parameters. 'params' is a tuple of
-        (k,d,n), where 'k' is the number of required shares, 'd' is the
-        shares_of_happiness, and 'n' is the total number of shares that will
-        be created.
-
-        Encoding parameters can be set in three ways. 1: The Encoder class
-        provides defaults (3/7/10). 2: the Encoder can be constructed with
-        an 'options' dictionary, in which the
-        needed_and_happy_and_total_shares' key can be a (k,d,n) tuple. 3:
-        set_params((k,d,n)) can be called.
-
-        If you intend to use set_params(), you must call it before
-        get_share_size or get_param are called.
-        """
 
     def set_encrypted_uploadable(u):
         """Provide a source of encrypted upload data. 'u' must implement
@@ -1271,7 +1647,7 @@ class IEncoder(Interface):
                          pushed.
 
         'share_counts': return a tuple describing how many shares are used:
-                        (needed_shares, shares_of_happiness, total_shares)
+                        (needed_shares, servers_of_happiness, total_shares)
 
         'num_segments': return an int with the number of segments that
                         will be encoded.
@@ -1304,11 +1680,13 @@ class IEncoder(Interface):
         Once this is called, set_size() and set_params() may not be called.
         """
 
-    def set_shareholders(shareholders):
+    def set_shareholders(shareholders, servermap):
         """Tell the encoder where to put the encoded shares. 'shareholders'
         must be a dictionary that maps share number (an integer ranging from
-        0 to n-1) to an instance that provides IStorageBucketWriter. This
-        must be performed before start() can be called."""
+        0 to n-1) to an instance that provides IStorageBucketWriter.
+        'servermap' is a dictionary that maps share number (as defined above)
+        to a set of peerids. This must be performed before start() can be
+        called."""
 
     def start():
         """Begin the encode/upload process. This involves reading encrypted
@@ -1323,6 +1701,7 @@ class IEncoder(Interface):
         sufficient to construct the read cap.
         """
 
+
 class IDecoder(Interface):
     """I take a list of shareholders and some setup information, then
     download, validate, decode, and decrypt data from them, writing the
@@ -1357,6 +1736,7 @@ class IDecoder(Interface):
         complete.
         """
 
+
 class IDownloadTarget(Interface):
     # Note that if the IDownloadTarget is also an IConsumer, the downloader
     # will register itself as a producer. This allows the target to invoke
@@ -1370,29 +1750,26 @@ class IDownloadTarget(Interface):
 
     def write(data):
         """Output some data to the target."""
+
     def close():
         """Inform the target that there is no more data to be written."""
+
     def fail(why):
         """fail() is called to indicate that the download has failed. 'why'
         is a Failure object indicating what went wrong. No further methods
         will be invoked on the IDownloadTarget after fail()."""
+
     def register_canceller(cb):
         """The CiphertextDownloader uses this to register a no-argument function
         that the target can call to cancel the download. Once this canceller
         is invoked, no further calls to write() or close() will be made."""
+
     def finish():
         """When the CiphertextDownloader is done, this finish() function will be
         called. Whatever it returns will be returned to the invoker of
         Downloader.download.
         """
-    # The following methods are just because that target might be a
-    # repairer.DownUpConnector, and just because the current CHKUpload object
-    # expects to find the storage index and encoding parameters in its
-    # Uploadable.
-    def set_storageindex(storageindex):
-        """ Set the storage index. """
-    def set_encodingparams(encodingparams):
-        """ Set the encoding parameters. """
+
 
 class IDownloader(Interface):
     def download(uri, target):
@@ -1402,6 +1779,7 @@ class IDownloader(Interface):
         Returns a Deferred that fires (with the results of target.finish)
         when the download is finished, or errbacks if something went wrong."""
 
+
 class IEncryptedUploadable(Interface):
     def set_upload_status(upload_status):
         """Provide an IUploadStatus object that should be filled with status
@@ -1440,37 +1818,10 @@ class IEncryptedUploadable(Interface):
         resuming an interrupted upload (where we need to compute the
         plaintext hashes, but don't need the redundant encrypted data)."""
 
-    def get_plaintext_hashtree_leaves(first, last, num_segments):
-        """OBSOLETE; Get the leaf nodes of a merkle hash tree over the
-        plaintext segments, i.e. get the tagged hashes of the given segments.
-        The segment size is expected to be generated by the
-        IEncryptedUploadable before any plaintext is read or ciphertext
-        produced, so that the segment hashes can be generated with only a
-        single pass.
-
-        This returns a Deferred which fires with a sequence of hashes, using:
-
-         tuple(segment_hashes[first:last])
-
-        'num_segments' is used to assert that the number of segments that the
-        IEncryptedUploadable handled matches the number of segments that the
-        encoder was expecting.
-
-        This method must not be called until the final byte has been read
-        from read_encrypted(). Once this method is called, read_encrypted()
-        can never be called again.
-        """
-
-    def get_plaintext_hash():
-        """OBSOLETE; Get the hash of the whole plaintext.
-
-        This returns a Deferred which fires with a tagged SHA-256 hash of the
-        whole plaintext, obtained from hashutil.plaintext_hash(data).
-        """
-
     def close():
         """Just like IUploadable.close()."""
 
+
 class IUploadable(Interface):
     def set_upload_status(upload_status):
         """Provide an IUploadStatus object that should be filled with status
@@ -1524,13 +1875,13 @@ class IUploadable(Interface):
         be used to encrypt the data. The key will also be hashed to derive
         the StorageIndex.
 
-        Uploadables which want to achieve convergence should hash their file
+        Uploadables that want to achieve convergence should hash their file
         contents and the serialized_encoding_parameters to form the key
         (which of course requires a full pass over the data). Uploadables can
         use the upload.ConvergentUploadMixin class to achieve this
         automatically.
 
-        Uploadables which do not care about convergence (or do not wish to
+        Uploadables that do not care about convergence (or do not wish to
         make multiple passes over the data) can simply return a
         strongly-random 16 byte string.
 
@@ -1540,14 +1891,18 @@ class IUploadable(Interface):
 
     def read(length):
         """Return a Deferred that fires with a list of strings (perhaps with
-        only a single element) which, when concatenated together, contain the
+        only a single element) that, when concatenated together, contain the
         next 'length' bytes of data. If EOF is near, this may provide fewer
         than 'length' bytes. The total number of bytes provided by read()
         before it signals EOF must equal the size provided by get_size().
 
         If the data must be acquired through multiple internal read
         operations, returning a list instead of a single string may help to
-        reduce string copies.
+        reduce string copies. However, the length of the concatenated strings
+        must equal the amount of data requested, unless EOF is encountered.
+        Long reads, or short reads without EOF, are not allowed. read()
+        should return the same amount of data as a local disk file read, just
+        in a different shape and asynchronously.
 
         'length' will typically be equal to (min(get_size(),1MB)/req_shares),
         so a 10kB file means length=3kB, 100kB file means length=30kB,
@@ -1563,42 +1918,99 @@ class IUploadable(Interface):
         """The upload is finished, and whatever filehandle was in use may be
         closed."""
 
+
+class IMutableUploadable(Interface):
+    """
+    I represent content that is due to be uploaded to a mutable filecap.
+    """
+    # This is somewhat simpler than the IUploadable interface above
+    # because mutable files do not need to be concerned with possibly
+    # generating a CHK, nor with per-file keys. It is a subset of the
+    # methods in IUploadable, though, so we could just as well implement
+    # the mutable uploadables as IUploadables that don't happen to use
+    # those methods (with the understanding that the unused methods will
+    # never be called on such objects)
+    def get_size():
+        """
+        Returns a Deferred that fires with the size of the content held
+        by the uploadable.
+        """
+
+    def read(length):
+        """
+        Returns a list of strings that, when concatenated, are the next
+        length bytes of the file, or fewer if there are fewer bytes
+        between the current location and the end of the file.
+        """
+
+    def close():
+        """
+        The process that used the Uploadable is finished using it, so
+        the uploadable may be closed.
+        """
+
+
 class IUploadResults(Interface):
-    """I am returned by upload() methods. I contain a number of public
-    attributes which can be read to determine the results of the upload. Some
-    of these are functional, some are timing information. All of these may be
-    None.
+    """I am returned by immutable upload() methods and contain the results of
+    the upload.
 
-     .file_size : the size of the file, in bytes
-     .uri : the CHK read-cap for the file
-     .ciphertext_fetched : how many bytes were fetched by the helper
-     .sharemap: dict mapping share identifier to set of serverids
-                   (binary strings). This indicates which servers were given
-                   which shares. For immutable files, the shareid is an
-                   integer (the share number, from 0 to N-1). For mutable
-                   files, it is a string of the form 'seq%d-%s-sh%d',
-                   containing the sequence number, the roothash, and the
-                   share number.
-     .servermap : dict mapping server peerid to a set of share numbers
-     .timings : dict of timing information, mapping name to seconds (float)
-       total : total upload time, start to finish
-       storage_index : time to compute the storage index
-       peer_selection : time to decide which peers will be used
-       contacting_helper : initial helper query to upload/no-upload decision
-       existence_check : helper pre-upload existence check
-       helper_total : initial helper query to helper finished pushing
-       cumulative_fetch : helper waiting for ciphertext requests
-       total_fetch : helper start to last ciphertext response
-       cumulative_encoding : just time spent in zfec
-       cumulative_sending : just time spent waiting for storage servers
-       hashes_and_close : last segment push to shareholder close
-       total_encode_and_push : first encode to shareholder close
+    Note that some of my methods return empty values (0 or an empty dict)
+    when called for non-distributed LIT files."""
+
+    def get_file_size():
+        """Return the file size, in bytes."""
+
+    def get_uri():
+        """Return the (string) URI of the object uploaded, a CHK readcap."""
+
+    def get_ciphertext_fetched():
+        """Return the number of bytes fetched by the helpe for this upload,
+        or 0 if the helper did not need to fetch any bytes (or if there was
+        no helper)."""
+
+    def get_preexisting_shares():
+        """Return the number of shares that were already present in the grid."""
+
+    def get_pushed_shares():
+        """Return the number of shares that were uploaded."""
+
+    def get_sharemap():
+        """Return a dict mapping share identifier to set of IServer
+        instances. This indicates which servers were given which shares. For
+        immutable files, the shareid is an integer (the share number, from 0
+        to N-1). For mutable files, it is a string of the form
+        'seq%d-%s-sh%d', containing the sequence number, the roothash, and
+        the share number."""
+
+    def get_servermap():
+        """Return dict mapping IServer instance to a set of share numbers."""
+
+    def get_timings():
+        """Return dict of timing information, mapping name to seconds. All
+        times are floats:
+          total : total upload time, start to finish
+          storage_index : time to compute the storage index
+          peer_selection : time to decide which peers will be used
+          contacting_helper : initial helper query to upload/no-upload decision
+          helper_total : initial helper query to helper finished pushing
+          cumulative_fetch : helper waiting for ciphertext requests
+          total_fetch : helper start to last ciphertext response
+          cumulative_encoding : just time spent in zfec
+          cumulative_sending : just time spent waiting for storage servers
+          hashes_and_close : last segment push to shareholder close
+          total_encode_and_push : first encode to shareholder close
+        """
+
+    def get_uri_extension_data():
+        """Return the dict of UEB data created for this file."""
+
+    def get_verifycapstr():
+        """Return the (string) verify-cap URI for the uploaded object."""
 
-    """
 
 class IDownloadResults(Interface):
     """I am created internally by download() methods. I contain a number of
-    public attributes which contain details about the download process.::
+    public attributes that contain details about the download process.::
 
      .file_size : the size of the file, in bytes
      .servers_used : set of server peerids that were used during download
@@ -1617,22 +2029,20 @@ class IDownloadResults(Interface):
        cumulative_decode : just time spent in zfec
        cumulative_decrypt : just time spent in decryption
        total : total download time, start to finish
-       fetch_per_server : dict of peerid to list of per-segment fetch times
-
+       fetch_per_server : dict of server to list of per-segment fetch times
     """
 
+
 class IUploader(Interface):
     def upload(uploadable):
         """Upload the file. 'uploadable' must impement IUploadable. This
-        returns a Deferred which fires with an UploadResults instance, from
+        returns a Deferred that fires with an IUploadResults instance, from
         which the URI of the file can be obtained as results.uri ."""
 
-    def upload_ssk(write_capability, new_version, uploadable):
-        """TODO: how should this work?"""
 
 class ICheckable(Interface):
     def check(monitor, verify=False, add_lease=False):
-        """Check upon my health, optionally repairing any problems.
+        """Check up on my health, optionally repairing any problems.
 
         This returns a Deferred that fires with an instance that provides
         ICheckResults, or None if the object is non-distributed (i.e. LIT
@@ -1674,7 +2084,7 @@ class ICheckable(Interface):
         kind of lease that is obtained (which account number to claim, etc).
 
         TODO: any problems seen during checking will be reported to the
-        health-manager.furl, a centralized object which is responsible for
+        health-manager.furl, a centralized object that is responsible for
         figuring out why files are unhealthy so corrective action can be
         taken.
         """
@@ -1689,9 +2099,10 @@ class ICheckable(Interface):
         will be put in the check-and-repair results. The Deferred will not
         fire until the repair is complete.
 
-        This returns a Deferred which fires with an instance of
+        This returns a Deferred that fires with an instance of
         ICheckAndRepairResults."""
 
+
 class IDeepCheckable(Interface):
     def start_deep_check(verify=False, add_lease=False):
         """Check upon the health of me and everything I can reach.
@@ -1725,14 +2136,17 @@ class IDeepCheckable(Interface):
         failure.
         """
 
+
 class ICheckResults(Interface):
     """I contain the detailed results of a check/verify operation.
     """
 
     def get_storage_index():
         """Return a string with the (binary) storage index."""
+
     def get_storage_index_string():
         """Return a string with the (printable) abbreviated storage index."""
+
     def get_uri():
         """Return the (string) URI of the object that was checked."""
 
@@ -1746,80 +2160,72 @@ class ICheckResults(Interface):
         not. Unrecoverable files are obviously unhealthy. Non-distributed LIT
         files always return True."""
 
-    def needs_rebalancing():
-        """Return a boolean, True if the file/dir's reliability could be
-        improved by moving shares to new servers. Non-distributed LIT files
-        always return False."""
-
-
-    def get_data():
-        """Return a dictionary that describes the state of the file/dir. LIT
-        files always return an empty dictionary. Normal files and directories
-        return a dictionary with the following keys (note that these use
-        binary strings rather than base32-encoded ones) (also note that for
-        mutable files, these counts are for the 'best' version):
-
-         count-shares-good: the number of distinct good shares that were found
-         count-shares-needed: 'k', the number of shares required for recovery
-         count-shares-expected: 'N', the number of total shares generated
-         count-good-share-hosts: the number of distinct storage servers with
-                                 good shares. If this number is less than
-                                 count-shares-good, then some shares are
-                                 doubled up, increasing the correlation of
-                                 failures. This indicates that one or more
-                                 shares should be moved to an otherwise unused
-                                 server, if one is available.
-         count-corrupt-shares: the number of shares with integrity failures
-         list-corrupt-shares: a list of 'share locators', one for each share
-                              that was found to be corrupt. Each share
-                              locator is a list of (serverid, storage_index,
-                              sharenum).
-         count-incompatible-shares: the number of shares which are of a share
-                                    format unknown to this checker
-         list-incompatible-shares: a list of 'share locators', one for each
-                                   share that was found to be of an unknown
-                                   format. Each share locator is a list of
-                                   (serverid, storage_index, sharenum).
-         servers-responding: list of (binary) storage server identifiers,
-                             one for each server which responded to the share
-                             query (even if they said they didn't have
-                             shares, and even if they said they did have
-                             shares but then didn't send them when asked, or
-                             dropped the connection, or returned a Failure,
-                             and even if they said they did have shares and
-                             sent incorrect ones when asked)
-         sharemap: dict mapping share identifier to list of serverids
-                   (binary strings). This indicates which servers are holding
-                   which shares. For immutable files, the shareid is an
-                   integer (the share number, from 0 to N-1). For mutable
-                   files, it is a string of the form 'seq%d-%s-sh%d',
-                   containing the sequence number, the roothash, and the
-                   share number.
-
-        The following keys are most relevant for mutable files, but immutable
-        files will provide sensible values too::
-
-         count-wrong-shares: the number of shares for versions other than the
-                             'best' one (which is defined as being the
-                             recoverable version with the highest sequence
-                             number, then the highest roothash). These are
-                             either leftover shares from an older version
-                             (perhaps on a server that was offline when an
-                             update occurred), shares from an unrecoverable
-                             newer version, or shares from an alternate
-                             current version that results from an
-                             uncoordinated write collision. For a healthy
-                             file, this will equal 0.
-
-         count-recoverable-versions: the number of recoverable versions of
-                                     the file. For a healthy file, this will
-                                     equal 1.
-
-         count-unrecoverable-versions: the number of unrecoverable versions
-                                       of the file. For a healthy file, this
-                                       will be 0.
+    # the following methods all return None for non-distributed LIT files
 
-        """
+    def get_happiness():
+        """Return the happiness count of the file."""
+
+    def get_encoding_needed():
+        """Return 'k', the number of shares required for recovery."""
+
+    def get_encoding_expected():
+        """Return 'N', the number of total shares generated."""
+
+    def get_share_counter_good():
+        """Return the number of distinct good shares that were found. For
+        mutable files, this counts shares for the 'best' version."""
+
+    def get_share_counter_wrong():
+        """For mutable files, return the number of shares for versions other
+        than the 'best' one (which is defined as being the recoverable
+        version with the highest sequence number, then the highest roothash).
+        These are either leftover shares from an older version (perhaps on a
+        server that was offline when an update occurred), shares from an
+        unrecoverable newer version, or shares from an alternate current
+        version that results from an uncoordinated write collision. For a
+        healthy file, this will equal 0. For immutable files, this will
+        always equal 0."""
+
+    def get_corrupt_shares():
+        """Return a list of 'share locators', one for each share that was
+        found to be corrupt (integrity failure). Each share locator is a list
+        of (IServer, storage_index, sharenum)."""
+
+    def get_incompatible_shares():
+        """Return a list of 'share locators', one for each share that was
+        found to be of an unknown format. Each share locator is a list of
+        (IServer, storage_index, sharenum)."""
+
+    def get_servers_responding():
+        """Return a list of IServer objects, one for each server that
+        responded to the share query (even if they said they didn't have
+        shares, and even if they said they did have shares but then didn't
+        send them when asked, or dropped the connection, or returned a
+        Failure, and even if they said they did have shares and sent
+        incorrect ones when asked)"""
+
+    def get_host_counter_good_shares():
+        """Return the number of distinct storage servers with good shares. If
+        this number is less than get_share_counters()[good], then some shares
+        are doubled up, increasing the correlation of failures. This
+        indicates that one or more shares should be moved to an otherwise
+        unused server, if one is available.
+        """
+
+    def get_version_counter_recoverable():
+        """Return the number of recoverable versions of the file. For a
+        healthy file, this will equal 1."""
+
+    def get_version_counter_unrecoverable():
+         """Return the number of unrecoverable versions of the file. For a
+         healthy file, this will be 0."""
+
+    def get_sharemap():
+        """Return a dict mapping share identifier to list of IServer objects.
+        This indicates which servers are holding which shares. For immutable
+        files, the shareid is an integer (the share number, from 0 to N-1).
+        For mutable files, it is a string of the form 'seq%d-%s-sh%d',
+        containing the sequence number, the roothash, and the share number."""
 
     def get_summary():
         """Return a string with a brief (one-line) summary of the results."""
@@ -1827,6 +2233,7 @@ class ICheckResults(Interface):
     def get_report():
         """Return a list of strings with more detailed results."""
 
+
 class ICheckAndRepairResults(Interface):
     """I contain the detailed results of a check/verify/repair operation.
 
@@ -1836,20 +2243,25 @@ class ICheckAndRepairResults(Interface):
 
     def get_storage_index():
         """Return a string with the (binary) storage index."""
+
     def get_storage_index_string():
         """Return a string with the (printable) abbreviated storage index."""
+
     def get_repair_attempted():
         """Return a boolean, True if a repair was attempted. We might not
         attempt to repair the file because it was healthy, or healthy enough
         (i.e. some shares were missing but not enough to exceed some
         threshold), or because we don't know how to repair this object."""
+
     def get_repair_successful():
         """Return a boolean, True if repair was attempted and the file/dir
         was fully healthy afterwards. False if no repair was attempted or if
         a repair attempt failed."""
+
     def get_pre_repair_results():
         """Return an ICheckResults instance that describes the state of the
         file/dir before any repair was attempted."""
+
     def get_post_repair_results():
         """Return an ICheckResults instance that describes the state of the
         file/dir after any repair was attempted. If no repair was attempted,
@@ -1865,6 +2277,7 @@ class IDeepCheckResults(Interface):
     def get_root_storage_index_string():
         """Return the storage index (abbreviated human-readable string) of
         the first object checked."""
+
     def get_counters():
         """Return a dictionary with the following keys::
 
@@ -1879,10 +2292,9 @@ class IDeepCheckResults(Interface):
         """
 
     def get_corrupt_shares():
-        """Return a set of (serverid, storage_index, sharenum) for all shares
-        that were found to be corrupt. Both serverid and storage_index are
-        binary.
-        """
+        """Return a set of (IServer, storage_index, sharenum) for all shares
+        that were found to be corrupt. storage_index is binary."""
+
     def get_all_results():
         """Return a dictionary mapping pathname (a tuple of strings, ready to
         be slash-joined) to an ICheckResults instance, one for each object
@@ -1897,6 +2309,7 @@ class IDeepCheckResults(Interface):
         """Return a dictionary with the same keys as
         IDirectoryNode.deep_stats()."""
 
+
 class IDeepCheckAndRepairResults(Interface):
     """I contain the results of a deep-check-and-repair operation.
 
@@ -1906,6 +2319,7 @@ class IDeepCheckAndRepairResults(Interface):
     def get_root_storage_index_string():
         """Return the storage index (abbreviated human-readable string) of
         the first object checked."""
+
     def get_counters():
         """Return a dictionary with the following keys::
 
@@ -1947,15 +2361,15 @@ class IDeepCheckAndRepairResults(Interface):
         IDirectoryNode.deep_stats()."""
 
     def get_corrupt_shares():
-        """Return a set of (serverid, storage_index, sharenum) for all shares
-        that were found to be corrupt before any repair was attempted. Both
-        serverid and storage_index are binary.
+        """Return a set of (IServer, storage_index, sharenum) for all shares
+        that were found to be corrupt before any repair was attempted.
+        storage_index is binary.
         """
     def get_remaining_corrupt_shares():
-        """Return a set of (serverid, storage_index, sharenum) for all shares
-        that were found to be corrupt after any repair was completed. Both
-        serverid and storage_index are binary. These are shares that need
-        manual inspection and probably deletion.
+        """Return a set of (IServer, storage_index, sharenum) for all shares
+        that were found to be corrupt after any repair was completed.
+        storage_index is binary. These are shares that need manual inspection
+        and probably deletion.
         """
     def get_all_results():
         """Return a dictionary mapping pathname (a tuple of strings, ready to
@@ -1989,8 +2403,13 @@ class IRepairable(Interface):
          return d
         """
 
+
 class IRepairResults(Interface):
     """I contain the results of a repair operation."""
+    def get_successful():
+        """Returns a boolean: True if the repair made the file healthy, False
+        if not. Repair failure generally indicates a file that has been
+        damaged beyond repair."""
 
 
 class IClient(Interface):
@@ -2002,17 +2421,28 @@ class IClient(Interface):
         """
 
     def create_mutable_file(contents=""):
-        """Create a new mutable file with contents, get back the URI string.
-        @param contents: the initial contents to place in the file.
-        @return: a Deferred that fires with tne (string) SSK URI for the new
-                 file.
+        """Create a new mutable file (with initial) contents, get back the
+        new node instance.
+
+        @param contents: (bytestring, callable, or None): this provides the
+        initial contents of the mutable file. If 'contents' is a bytestring,
+        it will be used as-is. If 'contents' is a callable, it will be
+        invoked with the new MutableFileNode instance and is expected to
+        return a bytestring with the initial contents of the file (the
+        callable can use node.get_writekey() to decide how to encrypt the
+        initial contents, e.g. for a brand new dirnode with initial
+        children). contents=None is equivalent to an empty string. Using
+        content_maker= is more efficient than creating a mutable file and
+        setting its contents in two separate operations.
+
+        @return: a Deferred that fires with an IMutableFileNode instance.
         """
 
     def create_dirnode(initial_children={}):
         """Create a new unattached dirnode, possibly with initial children.
 
         @param initial_children: dict with keys that are unicode child names,
-        and values that are (child_writecap, child_readcap, metadata) tuples.
+        and values that are (childnode, metadata) tuples.
 
         @return: a Deferred that fires with the new IDirectoryNode instance.
         """
@@ -2029,50 +2459,95 @@ class IClient(Interface):
 
         @return: an instance that provides IFilesystemNode (or more usefully
                  one of its subclasses). File-specifying URIs will result in
-                 IFileNode or IMutableFileNode -providing instances, like
-                 FileNode, LiteralFileNode, or MutableFileNode.
-                 Directory-specifying URIs will result in
-                 IDirectoryNode-providing instances, like DirectoryNode.
+                 IFileNode-providing instances, like ImmutableFileNode,
+                 LiteralFileNode, or MutableFileNode. Directory-specifying
+                 URIs will result in IDirectoryNode-providing instances, like
+                 DirectoryNode.
         """
 
+
+class INodeMaker(Interface):
+    """The NodeMaker is used to create IFilesystemNode instances. It can
+    accept a filecap/dircap string and return the node right away. It can
+    also create new nodes (i.e. upload a file, or create a mutable file)
+    asynchronously. Once you have one of these nodes, you can use other
+    methods to determine whether it is a file or directory, and to download
+    or modify its contents.
+
+    The NodeMaker encapsulates all the authorities that these
+    IFilesystemNodes require (like references to the StorageFarmBroker). Each
+    Tahoe process will typically have a single NodeMaker, but unit tests may
+    create simplified/mocked forms for testing purposes.
+    """
+
+    def create_from_cap(writecap, readcap=None, deep_immutable=False, name=u"<unknown name>"):
+        """I create an IFilesystemNode from the given writecap/readcap. I can
+        only provide nodes for existing file/directory objects: use my other
+        methods to create new objects. I return synchronously."""
+
+    def create_mutable_file(contents=None, keysize=None):
+        """I create a new mutable file, and return a Deferred that will fire
+        with the IMutableFileNode instance when it is ready. If contents= is
+        provided (a bytestring), it will be used as the initial contents of
+        the new file, otherwise the file will contain zero bytes. keysize= is
+        for use by unit tests, to create mutable files that are smaller than
+        usual."""
+
+    def create_new_mutable_directory(initial_children={}):
+        """I create a new mutable directory, and return a Deferred that will
+        fire with the IDirectoryNode instance when it is ready. If
+        initial_children= is provided (a dict mapping unicode child name to
+        (childnode, metadata_dict) tuples), the directory will be populated
+        with those children, otherwise it will be empty."""
+
+
 class IClientStatus(Interface):
     def list_all_uploads():
-        """Return a list of uploader objects, one for each upload which
+        """Return a list of uploader objects, one for each upload that
         currently has an object available (tracked with weakrefs). This is
         intended for debugging purposes."""
+
     def list_active_uploads():
         """Return a list of active IUploadStatus objects."""
+
     def list_recent_uploads():
         """Return a list of IUploadStatus objects for the most recently
         started uploads."""
 
     def list_all_downloads():
-        """Return a list of downloader objects, one for each download which
+        """Return a list of downloader objects, one for each download that
         currently has an object available (tracked with weakrefs). This is
         intended for debugging purposes."""
+
     def list_active_downloads():
         """Return a list of active IDownloadStatus objects."""
+
     def list_recent_downloads():
         """Return a list of IDownloadStatus objects for the most recently
         started downloads."""
 
+
 class IUploadStatus(Interface):
     def get_started():
         """Return a timestamp (float with seconds since epoch) indicating
         when the operation was started."""
+
     def get_storage_index():
         """Return a string with the (binary) storage index in use on this
         upload. Returns None if the storage index has not yet been
         calculated."""
+
     def get_size():
         """Return an integer with the number of bytes that will eventually
         be uploaded for this file. Returns None if the size is not yet known.
         """
     def using_helper():
         """Return True if this upload is using a Helper, False if not."""
+
     def get_status():
         """Return a string describing the current state of the upload
         process."""
+
     def get_progress():
         """Returns a tuple of floats, (chk, ciphertext, encode_and_push),
         each from 0.0 to 1.0 . 'chk' describes how much progress has been
@@ -2084,85 +2559,87 @@ class IUploadStatus(Interface):
         process has finished: for helper uploads this is dependent upon the
         helper providing progress reports. It might be reasonable to add all
         three numbers and report the sum to the user."""
+
     def get_active():
         """Return True if the upload is currently active, False if not."""
+
     def get_results():
         """Return an instance of UploadResults (which contains timing and
         sharemap information). Might return None if the upload is not yet
         finished."""
+
     def get_counter():
         """Each upload status gets a unique number: this method returns that
         number. This provides a handle to this particular upload, so a web
         page can generate a suitable hyperlink."""
 
+
 class IDownloadStatus(Interface):
     def get_started():
         """Return a timestamp (float with seconds since epoch) indicating
         when the operation was started."""
+
     def get_storage_index():
         """Return a string with the (binary) storage index in use on this
         download. This may be None if there is no storage index (i.e. LIT
         files)."""
+
     def get_size():
         """Return an integer with the number of bytes that will eventually be
         retrieved for this file. Returns None if the size is not yet known.
         """
+
     def using_helper():
         """Return True if this download is using a Helper, False if not."""
+
     def get_status():
         """Return a string describing the current state of the download
         process."""
+
     def get_progress():
         """Returns a float (from 0.0 to 1.0) describing the amount of the
         download that has completed. This value will remain at 0.0 until the
         first byte of plaintext is pushed to the download target."""
+
     def get_active():
         """Return True if the download is currently active, False if not."""
+
     def get_counter():
         """Each download status gets a unique number: this method returns
         that number. This provides a handle to this particular download, so a
         web page can generate a suitable hyperlink."""
 
+
 class IServermapUpdaterStatus(Interface):
     pass
+
 class IPublishStatus(Interface):
     pass
+
 class IRetrieveStatus(Interface):
     pass
 
+
 class NotCapableError(Exception):
     """You have tried to write to a read-only node."""
 
 class BadWriteEnablerError(Exception):
     pass
 
-class RIControlClient(RemoteInterface):
 
+class RIControlClient(RemoteInterface):
     def wait_for_client_connections(num_clients=int):
         """Do not return until we have connections to at least NUM_CLIENTS
         storage servers.
         """
 
-    def upload_from_file_to_uri(filename=str,
-                                convergence=ChoiceOf(None,
-                                                     StringConstraint(2**20))):
-        """Upload a file to the grid. This accepts a filename (which must be
-        absolute) that points to a file on the node's local disk. The node will
-        read the contents of this file, upload it to the grid, then return the
-        URI at which it was uploaded.  If convergence is None then a random
-        encryption key will be used, else the plaintext will be hashed, then
-        that hash will be mixed together with the "convergence" string to form
-        the encryption key.
-        """
-        return URI
+    # debug stuff
 
-    def download_from_uri_to_file(uri=URI, filename=str):
-        """Download a file from the grid, placing it on the node's local disk
-        at the given filename (which must be absolute[?]). Returns the
-        absolute filename where the file was written."""
+    def upload_random_data_from_file(size=int, convergence=str):
         return str
 
-    # debug stuff
+    def download_to_tempfile_and_delete(uri=str):
+        return None
 
     def get_memory_usage():
         """Return a dict describes the amount of memory currently in use. The
@@ -2190,10 +2667,12 @@ class RIControlClient(RemoteInterface):
         @return: a dictionary mapping peerid to a float (RTT time in seconds)
         """
 
-        return DictOf(Nodeid, float)
+        return DictOf(str, float)
+
 
 UploadResults = Any() #DictOf(str, str)
 
+
 class RIEncryptedUploadable(RemoteInterface):
     __remote_name__ = "RIEncryptedUploadable.tahoe.allmydata.com"
 
@@ -2259,12 +2738,13 @@ class RIStatsProvider(RemoteInterface):
     def get_stats():
         """
         returns a dictionary containing 'counters' and 'stats', each a
-        dictionary with string counter/stat name keys, and numeric values.
+        dictionary with string counter/stat name keys, and numeric or None values.
         counters are monotonically increasing measures of work done, and
         stats are instantaneous measures (potentially time averaged
         internally)
         """
-        return DictOf(str, DictOf(str, ChoiceOf(float, int, long)))
+        return DictOf(str, DictOf(str, ChoiceOf(float, int, long, None)))
+
 
 class RIStatsGatherer(RemoteInterface):
     __remote_name__ = "RIStatsGatherer.tahoe.allmydata.com"
@@ -2274,7 +2754,7 @@ class RIStatsGatherer(RemoteInterface):
 
     def provide(provider=RIStatsProvider, nickname=str):
         """
-        @param provider: a stats collector instance which should be polled
+        @param provider: a stats collector instance that should be polled
                          periodically by the gatherer to collect stats.
         @param nickname: a name useful to identify the provided client
         """
@@ -2305,16 +2785,22 @@ class RIKeyGenerator(RemoteInterface):
 class FileTooLargeError(Exception):
     pass
 
+
 class IValidatedThingProxy(Interface):
     def start():
-        """ Acquire a thing and validate it. Return a deferred which is
+        """ Acquire a thing and validate it. Return a deferred that is
         eventually fired with self if the thing is valid or errbacked if it
         can't be acquired or validated."""
 
+
 class InsufficientVersionError(Exception):
     def __init__(self, needed, got):
         self.needed = needed
         self.got = got
+
     def __repr__(self):
         return "InsufficientVersionError(need '%s', got %s)" % (self.needed,
                                                                 self.got)
+
+class EmptyPathnameComponentError(Exception):
+    """The webapi disallows empty pathname components."""