]> git.rkrishnan.org Git - tahoe-lafs/tahoe-lafs.git/blob - docs/specifications/mutable.rst
add user-oriented notes to NEWS and mutable.rst about SDMF-vs-MDMF
[tahoe-lafs/tahoe-lafs.git] / docs / specifications / mutable.rst
1 =============
2 Mutable Files
3 =============
4
5 This describes the "RSA-based mutable files" which were shipped in Tahoe v0.8.0.
6
7 1.  `Mutable Formats`_
8 2.  `Consistency vs. Availability`_
9 3.  `The Prime Coordination Directive: "Don't Do That"`_
10 4.  `Small Distributed Mutable Files`_
11
12     1. `SDMF slots overview`_
13     2. `Server Storage Protocol`_
14     3. `Code Details`_
15     4. `SMDF Slot Format`_
16     5. `Recovery`_
17
18 5.  `Medium Distributed Mutable Files`_
19 6.  `Large Distributed Mutable Files`_
20 7.  `TODO`_
21
22 Mutable File Slots are places with a stable identifier that can hold data
23 that changes over time. In contrast to CHK slots, for which the
24 URI/identifier is derived from the contents themselves, the Mutable File Slot
25 URI remains fixed for the life of the slot, regardless of what data is placed
26 inside it.
27
28 Each mutable slot is referenced by two different URIs. The "read-write" URI
29 grants read-write access to its holder, allowing them to put whatever
30 contents they like into the slot. The "read-only" URI is less powerful, only
31 granting read access, and not enabling modification of the data. The
32 read-write URI can be turned into the read-only URI, but not the other way
33 around.
34
35 The data in these slots is distributed over a number of servers, using the
36 same erasure coding that CHK files use, with 3-of-10 being a typical choice
37 of encoding parameters. The data is encrypted and signed in such a way that
38 only the holders of the read-write URI will be able to set the contents of
39 the slot, and only the holders of the read-only URI will be able to read
40 those contents. Holders of either URI will be able to validate the contents
41 as being written by someone with the read-write URI. The servers who hold the
42 shares cannot read or modify them: the worst they can do is deny service (by
43 deleting or corrupting the shares), or attempt a rollback attack (which can
44 only succeed with the cooperation of at least k servers).
45
46 Mutable Formats
47 ===============
48
49 When mutable files first shipped in Tahoe-0.8.0 (15-Feb-2008), the only
50 version available was "SDMF", described below. This was a
51 limited-functionality placeholder, intended to be replaced with
52 improved-efficiency "MDMF" files shortly afterwards. The development process
53 took longer than expected, and MDMF didn't ship until Tahoe-1.9.0
54 (31-Oct-2011), and even then it was opt-in (not used by default).
55
56 SDMF was intended for relatively small mutable files, up to a few megabytes.
57 It uses only one segment, so alacrity (the measure of how quickly the first
58 byte of plaintext is returned to the client) suffers, as the whole file must
59 be downloaded even if you only want to get a single byte. The memory used by
60 both clients and servers also scales with the size of the file, instead of
61 being limited to the half-a-MB-or-so that immutable file operations use, so
62 large files cause significant memory usage. To discourage the use of SDMF
63 outside it's design parameters, the early versions of Tahoe enforced a
64 maximum size on mutable files (maybe 10MB). Since most directories are built
65 out of mutable files, this imposed a limit of about 30k entries per
66 directory. In subsequent releases, this limit was removed, but the
67 performance problems inherent in the SDMF implementation remained.
68
69 In the summer of 2010, Google-Summer-of-Code student Kevan Carstensen took on
70 the project of finally implementing MDMF. Because of my (Brian) design
71 mistake in SDMF (not including a separate encryption seed in each segment),
72 the share format for SDMF could not be used for MDMF, resulting in a larger
73 gap between the two implementations (my original intention had been to make
74 SDMF a clean subset of MDMF, where any single-segment MDMF file could be
75 handled by the old SDMF code). In the fall of 2011, Kevan's code was finally
76 integrated, and first made available in the Tahoe-1.9.0 release.
77
78 The main improvement of MDMF is the use of multiple segments: individual
79 128KiB sections of the file can be retrieved or modified independently. The
80 improvement can be seen when fetching just a portion of the file (using a
81 Range: header on the webapi), or when modifying a portion (again with a
82 Range: header). It can also be seen indirectly when fetching the whole file:
83 the first segment of data should be delivered faster from a large MDMF file
84 than from an SDMF file, although the overall download will then proceed at
85 the same rate.
86
87 We've decided to make it opt-in for the first release while we shake out the
88 bugs, just in case a problem is found which requires an incompatible format
89 change. All new mutable files will be in SDMF format unless the user
90 specifically chooses to use MDMF instead. The code can read and modify
91 existing files of either format without user intervention. We expect to make
92 MDMF the default in a subsequent release, perhaps 2.0.
93
94 Which format should you use? SDMF works well for files up to a few MB, and
95 can be handled by older versions (Tahoe-1.8.3 and earlier). If you do not
96 need to support older clients, want to efficiently work with mutable files,
97 and have code which will use Range: headers that make partial reads and
98 writes, then MDMF is for you.
99
100
101 Consistency vs. Availability
102 ============================
103
104 There is an age-old battle between consistency and availability. Epic papers
105 have been written, elaborate proofs have been established, and generations of
106 theorists have learned that you cannot simultaneously achieve guaranteed
107 consistency with guaranteed reliability. In addition, the closer to 0 you get
108 on either axis, the cost and complexity of the design goes up.
109
110 Tahoe's design goals are to largely favor design simplicity, then slightly
111 favor read availability, over the other criteria.
112
113 As we develop more sophisticated mutable slots, the API may expose multiple
114 read versions to the application layer. The tahoe philosophy is to defer most
115 consistency recovery logic to the higher layers. Some applications have
116 effective ways to merge multiple versions, so inconsistency is not
117 necessarily a problem (i.e. directory nodes can usually merge multiple "add
118 child" operations).
119
120 The Prime Coordination Directive: "Don't Do That"
121 =================================================
122
123 The current rule for applications which run on top of Tahoe is "do not
124 perform simultaneous uncoordinated writes". That means you need non-tahoe
125 means to make sure that two parties are not trying to modify the same mutable
126 slot at the same time. For example:
127
128 * don't give the read-write URI to anyone else. Dirnodes in a private
129   directory generally satisfy this case, as long as you don't use two
130   clients on the same account at the same time
131 * if you give a read-write URI to someone else, stop using it yourself. An
132   inbox would be a good example of this.
133 * if you give a read-write URI to someone else, call them on the phone
134   before you write into it
135 * build an automated mechanism to have your agents coordinate writes.
136   For example, we expect a future release to include a FURL for a
137   "coordination server" in the dirnodes. The rule can be that you must
138   contact the coordination server and obtain a lock/lease on the file
139   before you're allowed to modify it.
140
141 If you do not follow this rule, Bad Things will happen. The worst-case Bad
142 Thing is that the entire file will be lost. A less-bad Bad Thing is that one
143 or more of the simultaneous writers will lose their changes. An observer of
144 the file may not see monotonically-increasing changes to the file, i.e. they
145 may see version 1, then version 2, then 3, then 2 again.
146
147 Tahoe takes some amount of care to reduce the badness of these Bad Things.
148 One way you can help nudge it from the "lose your file" case into the "lose
149 some changes" case is to reduce the number of competing versions: multiple
150 versions of the file that different parties are trying to establish as the
151 one true current contents. Each simultaneous writer counts as a "competing
152 version", as does the previous version of the file. If the count "S" of these
153 competing versions is larger than N/k, then the file runs the risk of being
154 lost completely. [TODO] If at least one of the writers remains running after
155 the collision is detected, it will attempt to recover, but if S>(N/k) and all
156 writers crash after writing a few shares, the file will be lost.
157
158 Note that Tahoe uses serialization internally to make sure that a single
159 Tahoe node will not perform simultaneous modifications to a mutable file. It
160 accomplishes this by using a weakref cache of the MutableFileNode (so that
161 there will never be two distinct MutableFileNodes for the same file), and by
162 forcing all mutable file operations to obtain a per-node lock before they
163 run. The Prime Coordination Directive therefore applies to inter-node
164 conflicts, not intra-node ones.
165
166
167 Small Distributed Mutable Files
168 ===============================
169
170 SDMF slots are suitable for small (<1MB) files that are editing by rewriting
171 the entire file. The three operations are:
172
173  * allocate (with initial contents)
174  * set (with new contents)
175  * get (old contents)
176
177 The first use of SDMF slots will be to hold directories (dirnodes), which map
178 encrypted child names to rw-URI/ro-URI pairs.
179
180 SDMF slots overview
181 -------------------
182
183 Each SDMF slot is created with a public/private key pair. The public key is
184 known as the "verification key", while the private key is called the
185 "signature key". The private key is hashed and truncated to 16 bytes to form
186 the "write key" (an AES symmetric key). The write key is then hashed and
187 truncated to form the "read key". The read key is hashed and truncated to
188 form the 16-byte "storage index" (a unique string used as an index to locate
189 stored data).
190
191 The public key is hashed by itself to form the "verification key hash".
192
193 The write key is hashed a different way to form the "write enabler master".
194 For each storage server on which a share is kept, the write enabler master is
195 concatenated with the server's nodeid and hashed, and the result is called
196 the "write enabler" for that particular server. Note that multiple shares of
197 the same slot stored on the same server will all get the same write enabler,
198 i.e. the write enabler is associated with the "bucket", rather than the
199 individual shares.
200
201 The private key is encrypted (using AES in counter mode) by the write key,
202 and the resulting crypttext is stored on the servers. so it will be
203 retrievable by anyone who knows the write key. The write key is not used to
204 encrypt anything else, and the private key never changes, so we do not need
205 an IV for this purpose.
206
207 The actual data is encrypted (using AES in counter mode) with a key derived
208 by concatenating the readkey with the IV, the hashing the results and
209 truncating to 16 bytes. The IV is randomly generated each time the slot is
210 updated, and stored next to the encrypted data.
211
212 The read-write URI consists of the write key and the verification key hash.
213 The read-only URI contains the read key and the verification key hash. The
214 verify-only URI contains the storage index and the verification key hash.
215
216 ::
217
218  URI:SSK-RW:b2a(writekey):b2a(verification_key_hash)
219  URI:SSK-RO:b2a(readkey):b2a(verification_key_hash)
220  URI:SSK-Verify:b2a(storage_index):b2a(verification_key_hash)
221
222 Note that this allows the read-only and verify-only URIs to be derived from
223 the read-write URI without actually retrieving the public keys. Also note
224 that it means the read-write agent must validate both the private key and the
225 public key when they are first fetched. All users validate the public key in
226 exactly the same way.
227
228 The SDMF slot is allocated by sending a request to the storage server with a
229 desired size, the storage index, and the write enabler for that server's
230 nodeid. If granted, the write enabler is stashed inside the slot's backing
231 store file. All further write requests must be accompanied by the write
232 enabler or they will not be honored. The storage server does not share the
233 write enabler with anyone else.
234
235 The SDMF slot structure will be described in more detail below. The important
236 pieces are:
237
238 * a sequence number
239 * a root hash "R"
240 * the encoding parameters (including k, N, file size, segment size)
241 * a signed copy of [seqnum,R,encoding_params], using the signature key
242 * the verification key (not encrypted)
243 * the share hash chain (part of a Merkle tree over the share hashes)
244 * the block hash tree (Merkle tree over blocks of share data)
245 * the share data itself (erasure-coding of read-key-encrypted file data)
246 * the signature key, encrypted with the write key
247
248 The access pattern for read is:
249
250 * hash read-key to get storage index
251 * use storage index to locate 'k' shares with identical 'R' values
252
253   * either get one share, read 'k' from it, then read k-1 shares
254   * or read, say, 5 shares, discover k, either get more or be finished
255   * or copy k into the URIs
256
257 * read verification key
258 * hash verification key, compare against verification key hash
259 * read seqnum, R, encoding parameters, signature
260 * verify signature against verification key
261 * read share data, compute block-hash Merkle tree and root "r"
262 * read share hash chain (leading from "r" to "R")
263 * validate share hash chain up to the root "R"
264 * submit share data to erasure decoding
265 * decrypt decoded data with read-key
266 * submit plaintext to application
267
268 The access pattern for write is:
269
270 * hash write-key to get read-key, hash read-key to get storage index
271 * use the storage index to locate at least one share
272 * read verification key and encrypted signature key
273 * decrypt signature key using write-key
274 * hash signature key, compare against write-key
275 * hash verification key, compare against verification key hash
276 * encrypt plaintext from application with read-key
277
278   * application can encrypt some data with the write-key to make it only
279     available to writers (use this for transitive read-onlyness of dirnodes)
280
281 * erasure-code crypttext to form shares
282 * split shares into blocks
283 * compute Merkle tree of blocks, giving root "r" for each share
284 * compute Merkle tree of shares, find root "R" for the file as a whole
285 * create share data structures, one per server:
286
287   * use seqnum which is one higher than the old version
288   * share hash chain has log(N) hashes, different for each server
289   * signed data is the same for each server
290
291 * now we have N shares and need homes for them
292 * walk through peers
293
294   * if share is not already present, allocate-and-set
295   * otherwise, try to modify existing share:
296   * send testv_and_writev operation to each one
297   * testv says to accept share if their(seqnum+R) <= our(seqnum+R)
298   * count how many servers wind up with which versions (histogram over R)
299   * keep going until N servers have the same version, or we run out of servers
300
301     * if any servers wound up with a different version, report error to
302       application
303     * if we ran out of servers, initiate recovery process (described below)
304
305 Server Storage Protocol
306 -----------------------
307
308 The storage servers will provide a mutable slot container which is oblivious
309 to the details of the data being contained inside it. Each storage index
310 refers to a "bucket", and each bucket has one or more shares inside it. (In a
311 well-provisioned network, each bucket will have only one share). The bucket
312 is stored as a directory, using the base32-encoded storage index as the
313 directory name. Each share is stored in a single file, using the share number
314 as the filename.
315
316 The container holds space for a container magic number (for versioning), the
317 write enabler, the nodeid which accepted the write enabler (used for share
318 migration, described below), a small number of lease structures, the embedded
319 data itself, and expansion space for additional lease structures::
320
321  #   offset    size    name
322  1   0         32      magic verstr "Tahoe mutable container v1\n\x75\x09\x44\x03\x8e"
323  2   32        20      write enabler's nodeid
324  3   52        32      write enabler
325  4   84        8       data size (actual share data present) (a)
326  5   92        8       offset of (8) count of extra leases (after data)
327  6   100       368     four leases, 92 bytes each
328                         0    4   ownerid (0 means "no lease here")
329                         4    4   expiration timestamp
330                         8   32   renewal token
331                         40  32   cancel token
332                         72  20   nodeid which accepted the tokens
333  7   468       (a)     data
334  8   ??        4       count of extra leases
335  9   ??        n*92    extra leases
336
337 The "extra leases" field must be copied and rewritten each time the size of
338 the enclosed data changes. The hope is that most buckets will have four or
339 fewer leases and this extra copying will not usually be necessary.
340
341 The (4) "data size" field contains the actual number of bytes of data present
342 in field (7), such that a client request to read beyond 504+(a) will result
343 in an error. This allows the client to (one day) read relative to the end of
344 the file. The container size (that is, (8)-(7)) might be larger, especially
345 if extra size was pre-allocated in anticipation of filling the container with
346 a lot of data.
347
348 The offset in (5) points at the *count* of extra leases, at (8). The actual
349 leases (at (9)) begin 4 bytes later. If the container size changes, both (8)
350 and (9) must be relocated by copying.
351
352 The server will honor any write commands that provide the write token and do
353 not exceed the server-wide storage size limitations. Read and write commands
354 MUST be restricted to the 'data' portion of the container: the implementation
355 of those commands MUST perform correct bounds-checking to make sure other
356 portions of the container are inaccessible to the clients.
357
358 The two methods provided by the storage server on these "MutableSlot" share
359 objects are:
360
361 * readv(ListOf(offset=int, length=int))
362
363   * returns a list of bytestrings, of the various requested lengths
364   * offset < 0 is interpreted relative to the end of the data
365   * spans which hit the end of the data will return truncated data
366
367 * testv_and_writev(write_enabler, test_vector, write_vector)
368
369   * this is a test-and-set operation which performs the given tests and only
370     applies the desired writes if all tests succeed. This is used to detect
371     simultaneous writers, and to reduce the chance that an update will lose
372     data recently written by some other party (written after the last time
373     this slot was read).
374   * test_vector=ListOf(TupleOf(offset, length, opcode, specimen))
375   * the opcode is a string, from the set [gt, ge, eq, le, lt, ne]
376   * each element of the test vector is read from the slot's data and 
377     compared against the specimen using the desired (in)equality. If all
378     tests evaluate True, the write is performed
379   * write_vector=ListOf(TupleOf(offset, newdata))
380
381     * offset < 0 is not yet defined, it probably means relative to the
382       end of the data, which probably means append, but we haven't nailed
383       it down quite yet
384     * write vectors are executed in order, which specifies the results of
385       overlapping writes
386
387   * return value:
388
389     * error: OutOfSpace
390     * error: something else (io error, out of memory, whatever)
391     * (True, old_test_data): the write was accepted (test_vector passed)
392     * (False, old_test_data): the write was rejected (test_vector failed)
393
394       * both 'accepted' and 'rejected' return the old data that was used
395         for the test_vector comparison. This can be used by the client
396         to detect write collisions, including collisions for which the
397         desired behavior was to overwrite the old version.
398
399 In addition, the storage server provides several methods to access these
400 share objects:
401
402 * allocate_mutable_slot(storage_index, sharenums=SetOf(int))
403
404   * returns DictOf(int, MutableSlot)
405
406 * get_mutable_slot(storage_index)
407
408   * returns DictOf(int, MutableSlot)
409   * or raises KeyError
410
411 We intend to add an interface which allows small slots to allocate-and-write
412 in a single call, as well as do update or read in a single call. The goal is
413 to allow a reasonably-sized dirnode to be created (or updated, or read) in
414 just one round trip (to all N shareholders in parallel).
415
416 migrating shares
417 ````````````````
418
419 If a share must be migrated from one server to another, two values become
420 invalid: the write enabler (since it was computed for the old server), and
421 the lease renew/cancel tokens.
422
423 Suppose that a slot was first created on nodeA, and was thus initialized with
424 WE(nodeA) (= H(WEM+nodeA)). Later, for provisioning reasons, the share is
425 moved from nodeA to nodeB.
426
427 Readers may still be able to find the share in its new home, depending upon
428 how many servers are present in the grid, where the new nodeid lands in the
429 permuted index for this particular storage index, and how many servers the
430 reading client is willing to contact.
431
432 When a client attempts to write to this migrated share, it will get a "bad
433 write enabler" error, since the WE it computes for nodeB will not match the
434 WE(nodeA) that was embedded in the share. When this occurs, the "bad write
435 enabler" message must include the old nodeid (e.g. nodeA) that was in the
436 share.
437
438 The client then computes H(nodeB+H(WEM+nodeA)), which is the same as
439 H(nodeB+WE(nodeA)). The client sends this along with the new WE(nodeB), which
440 is H(WEM+nodeB). Note that the client only sends WE(nodeB) to nodeB, never to
441 anyone else. Also note that the client does not send a value to nodeB that
442 would allow the node to impersonate the client to a third node: everything
443 sent to nodeB will include something specific to nodeB in it.
444
445 The server locally computes H(nodeB+WE(nodeA)), using its own node id and the
446 old write enabler from the share. It compares this against the value supplied
447 by the client. If they match, this serves as proof that the client was able
448 to compute the old write enabler. The server then accepts the client's new
449 WE(nodeB) and writes it into the container.
450
451 This WE-fixup process requires an extra round trip, and requires the error
452 message to include the old nodeid, but does not require any public key
453 operations on either client or server.
454
455 Migrating the leases will require a similar protocol. This protocol will be
456 defined concretely at a later date.
457
458 Code Details
459 ------------
460
461 The MutableFileNode class is used to manipulate mutable files (as opposed to
462 ImmutableFileNodes). These are initially generated with
463 client.create_mutable_file(), and later recreated from URIs with
464 client.create_node_from_uri(). Instances of this class will contain a URI and
465 a reference to the client (for peer selection and connection).
466
467 NOTE: this section is out of date. Please see src/allmydata/interfaces.py
468 (the section on IMutableFilesystemNode) for more accurate information.
469
470 The methods of MutableFileNode are:
471
472 * download_to_data() -> [deferred] newdata, NotEnoughSharesError
473
474   * if there are multiple retrieveable versions in the grid, get() returns
475     the first version it can reconstruct, and silently ignores the others.
476     In the future, a more advanced API will signal and provide access to
477     the multiple heads.
478
479 * update(newdata) -> OK, UncoordinatedWriteError, NotEnoughSharesError
480 * overwrite(newdata) -> OK, UncoordinatedWriteError, NotEnoughSharesError
481
482 download_to_data() causes a new retrieval to occur, pulling the current
483 contents from the grid and returning them to the caller. At the same time,
484 this call caches information about the current version of the file. This
485 information will be used in a subsequent call to update(), and if another
486 change has occured between the two, this information will be out of date,
487 triggering the UncoordinatedWriteError.
488
489 update() is therefore intended to be used just after a download_to_data(), in
490 the following pattern::
491
492  d = mfn.download_to_data()
493  d.addCallback(apply_delta)
494  d.addCallback(mfn.update)
495
496 If the update() call raises UCW, then the application can simply return an
497 error to the user ("you violated the Prime Coordination Directive"), and they
498 can try again later. Alternatively, the application can attempt to retry on
499 its own. To accomplish this, the app needs to pause, download the new
500 (post-collision and post-recovery) form of the file, reapply their delta,
501 then submit the update request again. A randomized pause is necessary to
502 reduce the chances of colliding a second time with another client that is
503 doing exactly the same thing::
504
505  d = mfn.download_to_data()
506  d.addCallback(apply_delta)
507  d.addCallback(mfn.update)
508  def _retry(f):
509    f.trap(UncoordinatedWriteError)
510    d1 = pause(random.uniform(5, 20))
511    d1.addCallback(lambda res: mfn.download_to_data())
512    d1.addCallback(apply_delta)
513    d1.addCallback(mfn.update)
514    return d1
515  d.addErrback(_retry)
516
517 Enthusiastic applications can retry multiple times, using a randomized
518 exponential backoff between each. A particularly enthusiastic application can
519 retry forever, but such apps are encouraged to provide a means to the user of
520 giving up after a while.
521
522 UCW does not mean that the update was not applied, so it is also a good idea
523 to skip the retry-update step if the delta was already applied::
524
525  d = mfn.download_to_data()
526  d.addCallback(apply_delta)
527  d.addCallback(mfn.update)
528  def _retry(f):
529    f.trap(UncoordinatedWriteError)
530    d1 = pause(random.uniform(5, 20))
531    d1.addCallback(lambda res: mfn.download_to_data())
532    def _maybe_apply_delta(contents):
533      new_contents = apply_delta(contents)
534      if new_contents != contents:
535        return mfn.update(new_contents)
536    d1.addCallback(_maybe_apply_delta)
537    return d1
538  d.addErrback(_retry)
539
540 update() is the right interface to use for delta-application situations, like
541 directory nodes (in which apply_delta might be adding or removing child
542 entries from a serialized table).
543
544 Note that any uncoordinated write has the potential to lose data. We must do
545 more analysis to be sure, but it appears that two clients who write to the
546 same mutable file at the same time (even if both eventually retry) will, with
547 high probability, result in one client observing UCW and the other silently
548 losing their changes. It is also possible for both clients to observe UCW.
549 The moral of the story is that the Prime Coordination Directive is there for
550 a reason, and that recovery/UCW/retry is not a subsitute for write
551 coordination.
552
553 overwrite() tells the client to ignore this cached version information, and
554 to unconditionally replace the mutable file's contents with the new data.
555 This should not be used in delta application, but rather in situations where
556 you want to replace the file's contents with completely unrelated ones. When
557 raw files are uploaded into a mutable slot through the Tahoe-LAFS web-API
558 (using POST and the ?mutable=true argument), they are put in place with
559 overwrite().
560
561 The peer-selection and data-structure manipulation (and signing/verification)
562 steps will be implemented in a separate class in allmydata/mutable.py .
563
564 SMDF Slot Format
565 ----------------
566
567 This SMDF data lives inside a server-side MutableSlot container. The server
568 is oblivious to this format.
569
570 This data is tightly packed. In particular, the share data is defined to run
571 all the way to the beginning of the encrypted private key (the encprivkey
572 offset is used both to terminate the share data and to begin the encprivkey).
573
574 ::
575
576   #    offset   size    name
577   1    0        1       version byte, \x00 for this format
578   2    1        8       sequence number. 2^64-1 must be handled specially, TBD
579   3    9        32      "R" (root of share hash Merkle tree)
580   4    41       16      IV (share data is AES(H(readkey+IV)) )
581   5    57       18      encoding parameters:
582         57       1        k
583         58       1        N
584         59       8        segment size
585         67       8        data length (of original plaintext)
586   6    75       32      offset table:
587         75       4        (8) signature
588         79       4        (9) share hash chain
589         83       4        (10) block hash tree
590         87       4        (11) share data
591         91       8        (12) encrypted private key
592         99       8        (13) EOF
593   7    107      436ish  verification key (2048 RSA key)
594   8    543ish   256ish  signature=RSAsign(sigkey, H(version+seqnum+r+IV+encparm))
595   9    799ish   (a)     share hash chain, encoded as:
596                          "".join([pack(">H32s", shnum, hash)
597                                   for (shnum,hash) in needed_hashes])
598  10    (927ish) (b)     block hash tree, encoded as:
599                          "".join([pack(">32s",hash) for hash in block_hash_tree])
600  11    (935ish) LEN     share data (no gap between this and encprivkey)
601  12    ??       1216ish encrypted private key= AESenc(write-key, RSA-key)
602  13    ??       --      EOF
603
604  (a) The share hash chain contains ceil(log(N)) hashes, each 32 bytes long.
605     This is the set of hashes necessary to validate this share's leaf in the
606     share Merkle tree. For N=10, this is 4 hashes, i.e. 128 bytes.
607  (b) The block hash tree contains ceil(length/segsize) hashes, each 32 bytes
608     long. This is the set of hashes necessary to validate any given block of
609     share data up to the per-share root "r". Each "r" is a leaf of the share
610     has tree (with root "R"), from which a minimal subset of hashes is put in
611     the share hash chain in (8).
612
613 Recovery
614 --------
615
616 The first line of defense against damage caused by colliding writes is the
617 Prime Coordination Directive: "Don't Do That".
618
619 The second line of defense is to keep "S" (the number of competing versions)
620 lower than N/k. If this holds true, at least one competing version will have
621 k shares and thus be recoverable. Note that server unavailability counts
622 against us here: the old version stored on the unavailable server must be
623 included in the value of S.
624
625 The third line of defense is our use of testv_and_writev() (described below),
626 which increases the convergence of simultaneous writes: one of the writers
627 will be favored (the one with the highest "R"), and that version is more
628 likely to be accepted than the others. This defense is least effective in the
629 pathological situation where S simultaneous writers are active, the one with
630 the lowest "R" writes to N-k+1 of the shares and then dies, then the one with
631 the next-lowest "R" writes to N-2k+1 of the shares and dies, etc, until the
632 one with the highest "R" writes to k-1 shares and dies. Any other sequencing
633 will allow the highest "R" to write to at least k shares and establish a new
634 revision.
635
636 The fourth line of defense is the fact that each client keeps writing until
637 at least one version has N shares. This uses additional servers, if
638 necessary, to make sure that either the client's version or some
639 newer/overriding version is highly available.
640
641 The fifth line of defense is the recovery algorithm, which seeks to make sure
642 that at least *one* version is highly available, even if that version is
643 somebody else's.
644
645 The write-shares-to-peers algorithm is as follows:
646
647 * permute peers according to storage index
648 * walk through peers, trying to assign one share per peer
649 * for each peer:
650
651   * send testv_and_writev, using "old(seqnum+R) <= our(seqnum+R)" as the test
652
653     * this means that we will overwrite any old versions, and we will
654       overwrite simultaenous writers of the same version if our R is higher.
655       We will not overwrite writers using a higher seqnum.
656
657   * record the version that each share winds up with. If the write was
658     accepted, this is our own version. If it was rejected, read the
659     old_test_data to find out what version was retained.
660   * if old_test_data indicates the seqnum was equal or greater than our
661     own, mark the "Simultanous Writes Detected" flag, which will eventually
662     result in an error being reported to the writer (in their close() call).
663   * build a histogram of "R" values
664   * repeat until the histogram indicate that some version (possibly ours)
665     has N shares. Use new servers if necessary.
666   * If we run out of servers:
667
668     * if there are at least shares-of-happiness of any one version, we're
669       happy, so return. (the close() might still get an error)
670     * not happy, need to reinforce something, goto RECOVERY
671
672 Recovery:
673
674 * read all shares, count the versions, identify the recoverable ones,
675   discard the unrecoverable ones.
676 * sort versions: locate max(seqnums), put all versions with that seqnum
677   in the list, sort by number of outstanding shares. Then put our own
678   version. (TODO: put versions with seqnum <max but >us ahead of us?).
679 * for each version:
680
681   * attempt to recover that version
682   * if not possible, remove it from the list, go to next one
683   * if recovered, start at beginning of peer list, push that version,
684     continue until N shares are placed
685   * if pushing our own version, bump up the seqnum to one higher than
686     the max seqnum we saw
687   * if we run out of servers:
688
689     * schedule retry and exponential backoff to repeat RECOVERY
690
691   * admit defeat after some period? presumeably the client will be shut down
692     eventually, maybe keep trying (once per hour?) until then.
693
694
695 Medium Distributed Mutable Files
696 ================================
697
698 These are just like the SDMF case, but:
699
700 * we actually take advantage of the Merkle hash tree over the blocks, by
701   reading a single segment of data at a time (and its necessary hashes), to
702   reduce the read-time alacrity
703 * we allow arbitrary writes to the file (i.e. seek() is provided, and
704   O_TRUNC is no longer required)
705 * we write more code on the client side (in the MutableFileNode class), to
706   first read each segment that a write must modify. This looks exactly like
707   the way a normal filesystem uses a block device, or how a CPU must perform
708   a cache-line fill before modifying a single word.
709 * we might implement some sort of copy-based atomic update server call,
710   to allow multiple writev() calls to appear atomic to any readers.
711
712 MDMF slots provide fairly efficient in-place edits of very large files (a few
713 GB). Appending data is also fairly efficient, although each time a power of 2
714 boundary is crossed, the entire file must effectively be re-uploaded (because
715 the size of the block hash tree changes), so if the filesize is known in
716 advance, that space ought to be pre-allocated (by leaving extra space between
717 the block hash tree and the actual data).
718
719 MDMF1 uses the Merkle tree to enable low-alacrity random-access reads. MDMF2
720 adds cache-line reads to allow random-access writes.
721
722 Large Distributed Mutable Files
723 ===============================
724
725 LDMF slots use a fundamentally different way to store the file, inspired by
726 Mercurial's "revlog" format. They enable very efficient insert/remove/replace
727 editing of arbitrary spans. Multiple versions of the file can be retained, in
728 a revision graph that can have multiple heads. Each revision can be
729 referenced by a cryptographic identifier. There are two forms of the URI, one
730 that means "most recent version", and a longer one that points to a specific
731 revision.
732
733 Metadata can be attached to the revisions, like timestamps, to enable rolling
734 back an entire tree to a specific point in history.
735
736 LDMF1 provides deltas but tries to avoid dealing with multiple heads. LDMF2
737 provides explicit support for revision identifiers and branching.
738
739 TODO
740 ====
741
742 improve allocate-and-write or get-writer-buckets API to allow one-call (or
743 maybe two-call) updates. The challenge is in figuring out which shares are on
744 which machines. First cut will have lots of round trips.
745
746 (eventually) define behavior when seqnum wraps. At the very least make sure
747 it can't cause a security problem. "the slot is worn out" is acceptable.
748
749 (eventually) define share-migration lease update protocol. Including the
750 nodeid who accepted the lease is useful, we can use the same protocol as we
751 do for updating the write enabler. However we need to know which lease to
752 update.. maybe send back a list of all old nodeids that we find, then try all
753 of them when we accept the update?
754
755 We now do this in a specially-formatted IndexError exception:
756  "UNABLE to renew non-existent lease. I have leases accepted by " +
757  "nodeids: '12345','abcde','44221' ."
758
759 confirm that a repairer can regenerate shares without the private key. Hmm,
760 without the write-enabler they won't be able to write those shares to the
761 servers.. although they could add immutable new shares to new servers.