]> git.rkrishnan.org Git - tahoe-lafs/tahoe-lafs.git/blob - src/allmydata/mutable/layout.py
mutable/layout.py: raise BadShareError instead of assert()
[tahoe-lafs/tahoe-lafs.git] / src / allmydata / mutable / layout.py
1
2 import struct
3 from allmydata.mutable.common import NeedMoreDataError, UnknownVersionError, \
4      BadShareError
5 from allmydata.interfaces import HASH_SIZE, SALT_SIZE, SDMF_VERSION, \
6                                  MDMF_VERSION, IMutableSlotWriter
7 from allmydata.util import mathutil
8 from twisted.python import failure
9 from twisted.internet import defer
10 from zope.interface import implements
11
12
13 # These strings describe the format of the packed structs they help process
14 # Here's what they mean:
15 #
16 #  PREFIX:
17 #    >: Big-endian byte order; the most significant byte is first (leftmost).
18 #    B: The version information; an 8 bit version identifier. Stored as
19 #       an unsigned char. This is currently 00 00 00 00; our modifications
20 #       will turn it into 00 00 00 01.
21 #    Q: The sequence number; this is sort of like a revision history for
22 #       mutable files; they start at 1 and increase as they are changed after
23 #       being uploaded. Stored as an unsigned long long, which is 8 bytes in
24 #       length.
25 #  32s: The root hash of the share hash tree. We use sha-256d, so we use 32 
26 #       characters = 32 bytes to store the value.
27 #  16s: The salt for the readkey. This is a 16-byte random value, stored as
28 #       16 characters.
29 #
30 #  SIGNED_PREFIX additions, things that are covered by the signature:
31 #    B: The "k" encoding parameter. We store this as an 8-bit character, 
32 #       which is convenient because our erasure coding scheme cannot 
33 #       encode if you ask for more than 255 pieces.
34 #    B: The "N" encoding parameter. Stored as an 8-bit character for the 
35 #       same reasons as above.
36 #    Q: The segment size of the uploaded file. This will essentially be the
37 #       length of the file in SDMF. An unsigned long long, so we can store 
38 #       files of quite large size.
39 #    Q: The data length of the uploaded file. Modulo padding, this will be
40 #       the same of the data length field. Like the data length field, it is
41 #       an unsigned long long and can be quite large.
42 #
43 #   HEADER additions:
44 #     L: The offset of the signature of this. An unsigned long.
45 #     L: The offset of the share hash chain. An unsigned long.
46 #     L: The offset of the block hash tree. An unsigned long.
47 #     L: The offset of the share data. An unsigned long.
48 #     Q: The offset of the encrypted private key. An unsigned long long, to
49 #        account for the possibility of a lot of share data.
50 #     Q: The offset of the EOF. An unsigned long long, to account for the
51 #        possibility of a lot of share data.
52
53 #  After all of these, we have the following:
54 #    - The verification key: Occupies the space between the end of the header
55 #      and the start of the signature (i.e.: data[HEADER_LENGTH:o['signature']].
56 #    - The signature, which goes from the signature offset to the share hash
57 #      chain offset.
58 #    - The share hash chain, which goes from the share hash chain offset to
59 #      the block hash tree offset.
60 #    - The share data, which goes from the share data offset to the encrypted
61 #      private key offset.
62 #    - The encrypted private key offset, which goes until the end of the file.
63
64 #  The block hash tree in this encoding has only one share, so the offset of
65 #  the share data will be 32 bits more than the offset of the block hash tree.
66 #  Given this, we may need to check to see how many bytes a reasonably sized
67 #  block hash tree will take up.
68
69 PREFIX = ">BQ32s16s" # each version has a different prefix
70 SIGNED_PREFIX = ">BQ32s16s BBQQ" # this is covered by the signature
71 SIGNED_PREFIX_LENGTH = struct.calcsize(SIGNED_PREFIX)
72 HEADER = ">BQ32s16s BBQQ LLLLQQ" # includes offsets
73 HEADER_LENGTH = struct.calcsize(HEADER)
74 OFFSETS = ">LLLLQQ"
75 OFFSETS_LENGTH = struct.calcsize(OFFSETS)
76
77 # These are still used for some tests.
78 def unpack_header(data):
79     o = {}
80     (version,
81      seqnum,
82      root_hash,
83      IV,
84      k, N, segsize, datalen,
85      o['signature'],
86      o['share_hash_chain'],
87      o['block_hash_tree'],
88      o['share_data'],
89      o['enc_privkey'],
90      o['EOF']) = struct.unpack(HEADER, data[:HEADER_LENGTH])
91     return (version, seqnum, root_hash, IV, k, N, segsize, datalen, o)
92
93 def unpack_share(data):
94     assert len(data) >= HEADER_LENGTH
95     o = {}
96     (version,
97      seqnum,
98      root_hash,
99      IV,
100      k, N, segsize, datalen,
101      o['signature'],
102      o['share_hash_chain'],
103      o['block_hash_tree'],
104      o['share_data'],
105      o['enc_privkey'],
106      o['EOF']) = struct.unpack(HEADER, data[:HEADER_LENGTH])
107
108     if version != 0:
109         raise UnknownVersionError("got mutable share version %d, but I only understand version 0" % version)
110
111     if len(data) < o['EOF']:
112         raise NeedMoreDataError(o['EOF'],
113                                 o['enc_privkey'], o['EOF']-o['enc_privkey'])
114
115     pubkey = data[HEADER_LENGTH:o['signature']]
116     signature = data[o['signature']:o['share_hash_chain']]
117     share_hash_chain_s = data[o['share_hash_chain']:o['block_hash_tree']]
118     share_hash_format = ">H32s"
119     hsize = struct.calcsize(share_hash_format)
120     if len(share_hash_chain_s) % hsize != 0:
121         raise BadShareError("hash chain is %d bytes, not multiple of %d"
122                             % (len(share_hash_chain_s), hsize))
123     share_hash_chain = []
124     for i in range(0, len(share_hash_chain_s), hsize):
125         chunk = share_hash_chain_s[i:i+hsize]
126         (hid, h) = struct.unpack(share_hash_format, chunk)
127         share_hash_chain.append( (hid, h) )
128     share_hash_chain = dict(share_hash_chain)
129     block_hash_tree_s = data[o['block_hash_tree']:o['share_data']]
130     if len(block_hash_tree_s) % 32 != 0:
131         raise BadShareError("block_hash_tree is %d bytes, not multiple of %d"
132                             % (len(block_hash_tree_s), 32))
133     block_hash_tree = []
134     for i in range(0, len(block_hash_tree_s), 32):
135         block_hash_tree.append(block_hash_tree_s[i:i+32])
136
137     share_data = data[o['share_data']:o['enc_privkey']]
138     enc_privkey = data[o['enc_privkey']:o['EOF']]
139
140     return (seqnum, root_hash, IV, k, N, segsize, datalen,
141             pubkey, signature, share_hash_chain, block_hash_tree,
142             share_data, enc_privkey)
143
144 def get_version_from_checkstring(checkstring):
145     (t, ) = struct.unpack(">B", checkstring[:1])
146     return t
147
148 def unpack_sdmf_checkstring(checkstring):
149     cs_len = struct.calcsize(PREFIX)
150     version, seqnum, root_hash, IV = struct.unpack(PREFIX, checkstring[:cs_len])
151     assert version == SDMF_VERSION, version
152     return (seqnum, root_hash, IV)
153
154 def unpack_mdmf_checkstring(checkstring):
155     cs_len = struct.calcsize(MDMFCHECKSTRING)
156     version, seqnum, root_hash = struct.unpack(MDMFCHECKSTRING, checkstring[:cs_len])
157     assert version == MDMF_VERSION, version
158     return (seqnum, root_hash)
159
160 def pack_offsets(verification_key_length, signature_length,
161                  share_hash_chain_length, block_hash_tree_length,
162                  share_data_length, encprivkey_length):
163     post_offset = HEADER_LENGTH
164     offsets = {}
165     o1 = offsets['signature'] = post_offset + verification_key_length
166     o2 = offsets['share_hash_chain'] = o1 + signature_length
167     o3 = offsets['block_hash_tree'] = o2 + share_hash_chain_length
168     o4 = offsets['share_data'] = o3 + block_hash_tree_length
169     o5 = offsets['enc_privkey'] = o4 + share_data_length
170     offsets['EOF'] = o5 + encprivkey_length
171
172     return struct.pack(">LLLLQQ",
173                        offsets['signature'],
174                        offsets['share_hash_chain'],
175                        offsets['block_hash_tree'],
176                        offsets['share_data'],
177                        offsets['enc_privkey'],
178                        offsets['EOF'])
179
180 def pack_share(prefix, verification_key, signature,
181                share_hash_chain, block_hash_tree,
182                share_data, encprivkey):
183     share_hash_chain_s = "".join([struct.pack(">H32s", i, share_hash_chain[i])
184                                   for i in sorted(share_hash_chain.keys())])
185     for h in block_hash_tree:
186         assert len(h) == 32
187     block_hash_tree_s = "".join(block_hash_tree)
188
189     offsets = pack_offsets(len(verification_key),
190                            len(signature),
191                            len(share_hash_chain_s),
192                            len(block_hash_tree_s),
193                            len(share_data),
194                            len(encprivkey))
195     final_share = "".join([prefix,
196                            offsets,
197                            verification_key,
198                            signature,
199                            share_hash_chain_s,
200                            block_hash_tree_s,
201                            share_data,
202                            encprivkey])
203     return final_share
204
205 def pack_prefix(seqnum, root_hash, IV,
206                 required_shares, total_shares,
207                 segment_size, data_length):
208     prefix = struct.pack(SIGNED_PREFIX,
209                          0, # version,
210                          seqnum,
211                          root_hash,
212                          IV,
213                          required_shares,
214                          total_shares,
215                          segment_size,
216                          data_length,
217                          )
218     return prefix
219
220
221 class SDMFSlotWriteProxy:
222     implements(IMutableSlotWriter)
223     """
224     I represent a remote write slot for an SDMF mutable file. I build a
225     share in memory, and then write it in one piece to the remote
226     server. This mimics how SDMF shares were built before MDMF (and the
227     new MDMF uploader), but provides that functionality in a way that
228     allows the MDMF uploader to be built without much special-casing for
229     file format, which makes the uploader code more readable.
230     """
231     def __init__(self,
232                  shnum,
233                  rref, # a remote reference to a storage server
234                  storage_index,
235                  secrets, # (write_enabler, renew_secret, cancel_secret)
236                  seqnum, # the sequence number of the mutable file
237                  required_shares,
238                  total_shares,
239                  segment_size,
240                  data_length): # the length of the original file
241         self.shnum = shnum
242         self._rref = rref
243         self._storage_index = storage_index
244         self._secrets = secrets
245         self._seqnum = seqnum
246         self._required_shares = required_shares
247         self._total_shares = total_shares
248         self._segment_size = segment_size
249         self._data_length = data_length
250
251         # This is an SDMF file, so it should have only one segment, so, 
252         # modulo padding of the data length, the segment size and the
253         # data length should be the same.
254         expected_segment_size = mathutil.next_multiple(data_length,
255                                                        self._required_shares)
256         assert expected_segment_size == segment_size
257
258         self._block_size = self._segment_size / self._required_shares
259
260         # This is meant to mimic how SDMF files were built before MDMF
261         # entered the picture: we generate each share in its entirety,
262         # then push it off to the storage server in one write. When
263         # callers call set_*, they are just populating this dict.
264         # finish_publishing will stitch these pieces together into a
265         # coherent share, and then write the coherent share to the
266         # storage server.
267         self._share_pieces = {}
268
269         # This tells the write logic what checkstring to use when
270         # writing remote shares.
271         self._testvs = []
272
273         self._readvs = [(0, struct.calcsize(PREFIX))]
274
275
276     def set_checkstring(self, checkstring_or_seqnum,
277                               root_hash=None,
278                               salt=None):
279         """
280         Set the checkstring that I will pass to the remote server when
281         writing.
282
283             @param checkstring_or_seqnum: A packed checkstring to use,
284                    or a sequence number. I will treat this as a checkstr
285
286         Note that implementations can differ in which semantics they
287         wish to support for set_checkstring -- they can, for example,
288         build the checkstring themselves from its constituents, or
289         some other thing.
290         """
291         if root_hash and salt:
292             checkstring = struct.pack(PREFIX,
293                                       0,
294                                       checkstring_or_seqnum,
295                                       root_hash,
296                                       salt)
297         else:
298             checkstring = checkstring_or_seqnum
299         self._testvs = [(0, len(checkstring), "eq", checkstring)]
300
301
302     def get_checkstring(self):
303         """
304         Get the checkstring that I think currently exists on the remote
305         server.
306         """
307         if self._testvs:
308             return self._testvs[0][3]
309         return ""
310
311
312     def put_block(self, data, segnum, salt):
313         """
314         Add a block and salt to the share.
315         """
316         # SDMF files have only one segment
317         assert segnum == 0
318         assert len(data) == self._block_size
319         assert len(salt) == SALT_SIZE
320
321         self._share_pieces['sharedata'] = data
322         self._share_pieces['salt'] = salt
323
324         # TODO: Figure out something intelligent to return.
325         return defer.succeed(None)
326
327
328     def put_encprivkey(self, encprivkey):
329         """
330         Add the encrypted private key to the share.
331         """
332         self._share_pieces['encprivkey'] = encprivkey
333
334         return defer.succeed(None)
335
336
337     def put_blockhashes(self, blockhashes):
338         """
339         Add the block hash tree to the share.
340         """
341         assert isinstance(blockhashes, list)
342         for h in blockhashes:
343             assert len(h) == HASH_SIZE
344
345         # serialize the blockhashes, then set them.
346         blockhashes_s = "".join(blockhashes)
347         self._share_pieces['block_hash_tree'] = blockhashes_s
348
349         return defer.succeed(None)
350
351
352     def put_sharehashes(self, sharehashes):
353         """
354         Add the share hash chain to the share.
355         """
356         assert isinstance(sharehashes, dict)
357         for h in sharehashes.itervalues():
358             assert len(h) == HASH_SIZE
359
360         # serialize the sharehashes, then set them.
361         sharehashes_s = "".join([struct.pack(">H32s", i, sharehashes[i])
362                                  for i in sorted(sharehashes.keys())])
363         self._share_pieces['share_hash_chain'] = sharehashes_s
364
365         return defer.succeed(None)
366
367
368     def put_root_hash(self, root_hash):
369         """
370         Add the root hash to the share.
371         """
372         assert len(root_hash) == HASH_SIZE
373
374         self._share_pieces['root_hash'] = root_hash
375
376         return defer.succeed(None)
377
378
379     def put_salt(self, salt):
380         """
381         Add a salt to an empty SDMF file.
382         """
383         assert len(salt) == SALT_SIZE
384
385         self._share_pieces['salt'] = salt
386         self._share_pieces['sharedata'] = ""
387
388
389     def get_signable(self):
390         """
391         Return the part of the share that needs to be signed.
392
393         SDMF writers need to sign the packed representation of the
394         first eight fields of the remote share, that is:
395             - version number (0)
396             - sequence number
397             - root of the share hash tree
398             - salt
399             - k
400             - n
401             - segsize
402             - datalen
403
404         This method is responsible for returning that to callers.
405         """
406         return struct.pack(SIGNED_PREFIX,
407                            0,
408                            self._seqnum,
409                            self._share_pieces['root_hash'],
410                            self._share_pieces['salt'],
411                            self._required_shares,
412                            self._total_shares,
413                            self._segment_size,
414                            self._data_length)
415
416
417     def put_signature(self, signature):
418         """
419         Add the signature to the share.
420         """
421         self._share_pieces['signature'] = signature
422
423         return defer.succeed(None)
424
425
426     def put_verification_key(self, verification_key):
427         """
428         Add the verification key to the share.
429         """
430         self._share_pieces['verification_key'] = verification_key
431
432         return defer.succeed(None)
433
434
435     def get_verinfo(self):
436         """
437         I return my verinfo tuple. This is used by the ServermapUpdater
438         to keep track of versions of mutable files.
439
440         The verinfo tuple for MDMF files contains:
441             - seqnum
442             - root hash
443             - a blank (nothing)
444             - segsize
445             - datalen
446             - k
447             - n
448             - prefix (the thing that you sign)
449             - a tuple of offsets
450
451         We include the nonce in MDMF to simplify processing of version
452         information tuples.
453
454         The verinfo tuple for SDMF files is the same, but contains a
455         16-byte IV instead of a hash of salts.
456         """
457         return (self._seqnum,
458                 self._share_pieces['root_hash'],
459                 self._share_pieces['salt'],
460                 self._segment_size,
461                 self._data_length,
462                 self._required_shares,
463                 self._total_shares,
464                 self.get_signable(),
465                 self._get_offsets_tuple())
466
467     def _get_offsets_dict(self):
468         post_offset = HEADER_LENGTH
469         offsets = {}
470
471         verification_key_length = len(self._share_pieces['verification_key'])
472         o1 = offsets['signature'] = post_offset + verification_key_length
473
474         signature_length = len(self._share_pieces['signature'])
475         o2 = offsets['share_hash_chain'] = o1 + signature_length
476
477         share_hash_chain_length = len(self._share_pieces['share_hash_chain'])
478         o3 = offsets['block_hash_tree'] = o2 + share_hash_chain_length
479
480         block_hash_tree_length = len(self._share_pieces['block_hash_tree'])
481         o4 = offsets['share_data'] = o3 + block_hash_tree_length
482
483         share_data_length = len(self._share_pieces['sharedata'])
484         o5 = offsets['enc_privkey'] = o4 + share_data_length
485
486         encprivkey_length = len(self._share_pieces['encprivkey'])
487         offsets['EOF'] = o5 + encprivkey_length
488         return offsets
489
490
491     def _get_offsets_tuple(self):
492         offsets = self._get_offsets_dict()
493         return tuple([(key, value) for key, value in offsets.items()])
494
495
496     def _pack_offsets(self):
497         offsets = self._get_offsets_dict()
498         return struct.pack(">LLLLQQ",
499                            offsets['signature'],
500                            offsets['share_hash_chain'],
501                            offsets['block_hash_tree'],
502                            offsets['share_data'],
503                            offsets['enc_privkey'],
504                            offsets['EOF'])
505
506
507     def finish_publishing(self):
508         """
509         Do anything necessary to finish writing the share to a remote
510         server. I require that no further publishing needs to take place
511         after this method has been called.
512         """
513         for k in ["sharedata", "encprivkey", "signature", "verification_key",
514                   "share_hash_chain", "block_hash_tree"]:
515             assert k in self._share_pieces, (self.shnum, k, self._share_pieces.keys())
516         # This is the only method that actually writes something to the
517         # remote server.
518         # First, we need to pack the share into data that we can write
519         # to the remote server in one write.
520         offsets = self._pack_offsets()
521         prefix = self.get_signable()
522         final_share = "".join([prefix,
523                                offsets,
524                                self._share_pieces['verification_key'],
525                                self._share_pieces['signature'],
526                                self._share_pieces['share_hash_chain'],
527                                self._share_pieces['block_hash_tree'],
528                                self._share_pieces['sharedata'],
529                                self._share_pieces['encprivkey']])
530
531         # Our only data vector is going to be writing the final share,
532         # in its entirely.
533         datavs = [(0, final_share)]
534
535         if not self._testvs:
536             # Our caller has not provided us with another checkstring
537             # yet, so we assume that we are writing a new share, and set
538             # a test vector that will allow a new share to be written.
539             self._testvs = []
540             self._testvs.append(tuple([0, 1, "eq", ""]))
541
542         tw_vectors = {}
543         tw_vectors[self.shnum] = (self._testvs, datavs, None)
544         return self._rref.callRemote("slot_testv_and_readv_and_writev",
545                                      self._storage_index,
546                                      self._secrets,
547                                      tw_vectors,
548                                      # TODO is it useful to read something?
549                                      self._readvs)
550
551
552 MDMFHEADER = ">BQ32sBBQQ QQQQQQQQ"
553 MDMFHEADERWITHOUTOFFSETS = ">BQ32sBBQQ"
554 MDMFHEADERSIZE = struct.calcsize(MDMFHEADER)
555 MDMFHEADERWITHOUTOFFSETSSIZE = struct.calcsize(MDMFHEADERWITHOUTOFFSETS)
556 MDMFCHECKSTRING = ">BQ32s"
557 MDMFSIGNABLEHEADER = ">BQ32sBBQQ"
558 MDMFOFFSETS = ">QQQQQQQQ"
559 MDMFOFFSETS_LENGTH = struct.calcsize(MDMFOFFSETS)
560
561 PRIVATE_KEY_SIZE = 1220
562 SIGNATURE_SIZE = 260
563 VERIFICATION_KEY_SIZE = 292
564 # We know we won't have more than 256 shares, and we know that we won't need
565 # to store more than ln2(256) hash-chain nodes to validate, so that's our
566 # bound. Each node requires 2 bytes of node-number plus 32 bytes of hash.
567 SHARE_HASH_CHAIN_SIZE = (2+HASH_SIZE)*mathutil.log_ceil(256, 2)
568
569 class MDMFSlotWriteProxy:
570     implements(IMutableSlotWriter)
571
572     """
573     I represent a remote write slot for an MDMF mutable file.
574
575     I abstract away from my caller the details of block and salt
576     management, and the implementation of the on-disk format for MDMF
577     shares.
578     """
579     # Expected layout, MDMF:
580     # offset:     size:       name:
581     #-- signed part --
582     # 0           1           version number (01)
583     # 1           8           sequence number
584     # 9           32          share tree root hash
585     # 41          1           The "k" encoding parameter
586     # 42          1           The "N" encoding parameter
587     # 43          8           The segment size of the uploaded file
588     # 51          8           The data length of the original plaintext
589     #-- end signed part --
590     # 59          8           The offset of the encrypted private key
591     # 67          8           The offset of the share hash chain
592     # 75          8           The offset of the signature
593     # 83          8           The offset of the verification key
594     # 91          8           The offset of the end of the v. key.
595     # 99          8           The offset of the share data
596     # 107         8           The offset of the block hash tree
597     # 115         8           The offset of EOF
598     # 123         var         encrypted private key
599     # var         var         share hash chain
600     # var         var         signature
601     # var         var         verification key
602     # var         large       share data
603     # var         var         block hash tree
604     #
605     # We order the fields that way to make smart downloaders -- downloaders
606     # which prempetively read a big part of the share -- possible.
607     #
608     # The checkstring is the first three fields -- the version number,
609     # sequence number, root hash and root salt hash. This is consistent
610     # in meaning to what we have with SDMF files, except now instead of
611     # using the literal salt, we use a value derived from all of the
612     # salts -- the share hash root.
613     # 
614     # The salt is stored before the block for each segment. The block
615     # hash tree is computed over the combination of block and salt for
616     # each segment. In this way, we get integrity checking for both
617     # block and salt with the current block hash tree arrangement.
618     # 
619     # The ordering of the offsets is different to reflect the dependencies
620     # that we'll run into with an MDMF file. The expected write flow is
621     # something like this:
622     #
623     #   0: Initialize with the sequence number, encoding parameters and
624     #      data length. From this, we can deduce the number of segments,
625     #      and where they should go.. We can also figure out where the
626     #      encrypted private key should go, because we can figure out how
627     #      big the share data will be.
628     # 
629     #   1: Encrypt, encode, and upload the file in chunks. Do something
630     #      like 
631     #
632     #       put_block(data, segnum, salt)
633     #
634     #      to write a block and a salt to the disk. We can do both of
635     #      these operations now because we have enough of the offsets to
636     #      know where to put them.
637     # 
638     #   2: Put the encrypted private key. Use:
639     #
640     #        put_encprivkey(encprivkey)
641     #
642     #      Now that we know the length of the private key, we can fill
643     #      in the offset for the block hash tree.
644     #
645     #   3: We're now in a position to upload the block hash tree for
646     #      a share. Put that using something like:
647     #       
648     #        put_blockhashes(block_hash_tree)
649     #
650     #      Note that block_hash_tree is a list of hashes -- we'll take
651     #      care of the details of serializing that appropriately. When
652     #      we get the block hash tree, we are also in a position to
653     #      calculate the offset for the share hash chain, and fill that
654     #      into the offsets table.
655     #
656     #   4: We're now in a position to upload the share hash chain for
657     #      a share. Do that with something like:
658     #      
659     #        put_sharehashes(share_hash_chain) 
660     #
661     #      share_hash_chain should be a dictionary mapping shnums to 
662     #      32-byte hashes -- the wrapper handles serialization.
663     #      We'll know where to put the signature at this point, also.
664     #      The root of this tree will be put explicitly in the next
665     #      step.
666     # 
667     #   5: Before putting the signature, we must first put the
668     #      root_hash. Do this with:
669     # 
670     #        put_root_hash(root_hash).
671     #      
672     #      In terms of knowing where to put this value, it was always
673     #      possible to place it, but it makes sense semantically to
674     #      place it after the share hash tree, so that's why you do it
675     #      in this order.
676     #
677     #   6: With the root hash put, we can now sign the header. Use:
678     #
679     #        get_signable()
680     #
681     #      to get the part of the header that you want to sign, and use:
682     #       
683     #        put_signature(signature)
684     #
685     #      to write your signature to the remote server.
686     #
687     #   6: Add the verification key, and finish. Do:
688     #
689     #        put_verification_key(key) 
690     #
691     #      and 
692     #
693     #        finish_publish()
694     #
695     # Checkstring management:
696     # 
697     # To write to a mutable slot, we have to provide test vectors to ensure
698     # that we are writing to the same data that we think we are. These
699     # vectors allow us to detect uncoordinated writes; that is, writes
700     # where both we and some other shareholder are writing to the
701     # mutable slot, and to report those back to the parts of the program
702     # doing the writing. 
703     #
704     # With SDMF, this was easy -- all of the share data was written in
705     # one go, so it was easy to detect uncoordinated writes, and we only
706     # had to do it once. With MDMF, not all of the file is written at
707     # once.
708     #
709     # If a share is new, we write out as much of the header as we can
710     # before writing out anything else. This gives other writers a
711     # canary that they can use to detect uncoordinated writes, and, if
712     # they do the same thing, gives us the same canary. We them update
713     # the share. We won't be able to write out two fields of the header
714     # -- the share tree hash and the salt hash -- until we finish
715     # writing out the share. We only require the writer to provide the
716     # initial checkstring, and keep track of what it should be after
717     # updates ourselves.
718     #
719     # If we haven't written anything yet, then on the first write (which
720     # will probably be a block + salt of a share), we'll also write out
721     # the header. On subsequent passes, we'll expect to see the header.
722     # This changes in two places:
723     #
724     #   - When we write out the salt hash
725     #   - When we write out the root of the share hash tree
726     #
727     # since these values will change the header. It is possible that we 
728     # can just make those be written in one operation to minimize
729     # disruption.
730     def __init__(self,
731                  shnum,
732                  rref, # a remote reference to a storage server
733                  storage_index,
734                  secrets, # (write_enabler, renew_secret, cancel_secret)
735                  seqnum, # the sequence number of the mutable file
736                  required_shares,
737                  total_shares,
738                  segment_size,
739                  data_length): # the length of the original file
740         self.shnum = shnum
741         self._rref = rref
742         self._storage_index = storage_index
743         self._seqnum = seqnum
744         self._required_shares = required_shares
745         assert self.shnum >= 0 and self.shnum < total_shares
746         self._total_shares = total_shares
747         # We build up the offset table as we write things. It is the
748         # last thing we write to the remote server. 
749         self._offsets = {}
750         self._testvs = []
751         # This is a list of write vectors that will be sent to our
752         # remote server once we are directed to write things there.
753         self._writevs = []
754         self._secrets = secrets
755         # The segment size needs to be a multiple of the k parameter --
756         # any padding should have been carried out by the publisher
757         # already.
758         assert segment_size % required_shares == 0
759         self._segment_size = segment_size
760         self._data_length = data_length
761
762         # These are set later -- we define them here so that we can
763         # check for their existence easily
764
765         # This is the root of the share hash tree -- the Merkle tree
766         # over the roots of the block hash trees computed for shares in
767         # this upload.
768         self._root_hash = None
769
770         # We haven't yet written anything to the remote bucket. By
771         # setting this, we tell the _write method as much. The write
772         # method will then know that it also needs to add a write vector
773         # for the checkstring (or what we have of it) to the first write
774         # request. We'll then record that value for future use.  If
775         # we're expecting something to be there already, we need to call
776         # set_checkstring before we write anything to tell the first
777         # write about that.
778         self._written = False
779
780         # When writing data to the storage servers, we get a read vector
781         # for free. We'll read the checkstring, which will help us
782         # figure out what's gone wrong if a write fails.
783         self._readv = [(0, struct.calcsize(MDMFCHECKSTRING))]
784
785         # We calculate the number of segments because it tells us
786         # where the salt part of the file ends/share segment begins,
787         # and also because it provides a useful amount of bounds checking.
788         self._num_segments = mathutil.div_ceil(self._data_length,
789                                                self._segment_size)
790         self._block_size = self._segment_size / self._required_shares
791         # We also calculate the share size, to help us with block
792         # constraints later.
793         tail_size = self._data_length % self._segment_size
794         if not tail_size:
795             self._tail_block_size = self._block_size
796         else:
797             self._tail_block_size = mathutil.next_multiple(tail_size,
798                                                            self._required_shares)
799             self._tail_block_size /= self._required_shares
800
801         # We already know where the sharedata starts; right after the end
802         # of the header (which is defined as the signable part + the offsets)
803         # We can also calculate where the encrypted private key begins
804         # from what we know know.
805         self._actual_block_size = self._block_size + SALT_SIZE
806         data_size = self._actual_block_size * (self._num_segments - 1)
807         data_size += self._tail_block_size
808         data_size += SALT_SIZE
809         self._offsets['enc_privkey'] = MDMFHEADERSIZE
810
811         # We don't define offsets for these because we want them to be
812         # tightly packed -- this allows us to ignore the responsibility
813         # of padding individual values, and of removing that padding
814         # later. So nonconstant_start is where we start writing
815         # nonconstant data.
816         nonconstant_start = self._offsets['enc_privkey']
817         nonconstant_start += PRIVATE_KEY_SIZE
818         nonconstant_start += SIGNATURE_SIZE
819         nonconstant_start += VERIFICATION_KEY_SIZE
820         nonconstant_start += SHARE_HASH_CHAIN_SIZE
821
822         self._offsets['share_data'] = nonconstant_start
823
824         # Finally, we know how big the share data will be, so we can
825         # figure out where the block hash tree needs to go.
826         # XXX: But this will go away if Zooko wants to make it so that
827         # you don't need to know the size of the file before you start
828         # uploading it.
829         self._offsets['block_hash_tree'] = self._offsets['share_data'] + \
830                     data_size
831
832         # Done. We can snow start writing.
833
834
835     def set_checkstring(self,
836                         seqnum_or_checkstring,
837                         root_hash=None,
838                         salt=None):
839         """
840         Set checkstring checkstring for the given shnum.
841
842         This can be invoked in one of two ways.
843
844         With one argument, I assume that you are giving me a literal
845         checkstring -- e.g., the output of get_checkstring. I will then
846         set that checkstring as it is. This form is used by unit tests.
847
848         With two arguments, I assume that you are giving me a sequence
849         number and root hash to make a checkstring from. In that case, I
850         will build a checkstring and set it for you. This form is used
851         by the publisher.
852
853         By default, I assume that I am writing new shares to the grid.
854         If you don't explcitly set your own checkstring, I will use
855         one that requires that the remote share not exist. You will want
856         to use this method if you are updating a share in-place;
857         otherwise, writes will fail.
858         """
859         # You're allowed to overwrite checkstrings with this method;
860         # I assume that users know what they are doing when they call
861         # it.
862         if root_hash:
863             checkstring = struct.pack(MDMFCHECKSTRING,
864                                       1,
865                                       seqnum_or_checkstring,
866                                       root_hash)
867         else:
868             checkstring = seqnum_or_checkstring
869
870         if checkstring == "":
871             # We special-case this, since len("") = 0, but we need
872             # length of 1 for the case of an empty share to work on the
873             # storage server, which is what a checkstring that is the
874             # empty string means.
875             self._testvs = []
876         else:
877             self._testvs = []
878             self._testvs.append((0, len(checkstring), "eq", checkstring))
879
880
881     def __repr__(self):
882         return "MDMFSlotWriteProxy for share %d" % self.shnum
883
884
885     def get_checkstring(self):
886         """
887         Given a share number, I return a representation of what the
888         checkstring for that share on the server will look like.
889
890         I am mostly used for tests.
891         """
892         if self._root_hash:
893             roothash = self._root_hash
894         else:
895             roothash = "\x00" * 32
896         return struct.pack(MDMFCHECKSTRING,
897                            1,
898                            self._seqnum,
899                            roothash)
900
901
902     def put_block(self, data, segnum, salt):
903         """
904         I queue a write vector for the data, salt, and segment number
905         provided to me. I return None, as I do not actually cause
906         anything to be written yet.
907         """
908         if segnum >= self._num_segments:
909             raise LayoutInvalid("I won't overwrite the block hash tree")
910         if len(salt) != SALT_SIZE:
911             raise LayoutInvalid("I was given a salt of size %d, but "
912                                 "I wanted a salt of size %d")
913         if segnum + 1 == self._num_segments:
914             if len(data) != self._tail_block_size:
915                 raise LayoutInvalid("I was given the wrong size block to write")
916         elif len(data) != self._block_size:
917             raise LayoutInvalid("I was given the wrong size block to write")
918
919         # We want to write at len(MDMFHEADER) + segnum * block_size.
920         offset = self._offsets['share_data'] + \
921             (self._actual_block_size * segnum)
922         data = salt + data
923
924         self._writevs.append(tuple([offset, data]))
925
926
927     def put_encprivkey(self, encprivkey):
928         """
929         I queue a write vector for the encrypted private key provided to
930         me.
931         """
932         assert self._offsets
933         assert self._offsets['enc_privkey']
934         # You shouldn't re-write the encprivkey after the block hash
935         # tree is written, since that could cause the private key to run
936         # into the block hash tree. Before it writes the block hash
937         # tree, the block hash tree writing method writes the offset of
938         # the share hash chain. So that's a good indicator of whether or
939         # not the block hash tree has been written.
940         if "signature" in self._offsets:
941             raise LayoutInvalid("You can't put the encrypted private key "
942                                 "after putting the share hash chain")
943
944         self._offsets['share_hash_chain'] = self._offsets['enc_privkey'] + \
945                 len(encprivkey)
946
947         self._writevs.append(tuple([self._offsets['enc_privkey'], encprivkey]))
948
949
950     def put_blockhashes(self, blockhashes):
951         """
952         I queue a write vector to put the block hash tree in blockhashes
953         onto the remote server.
954
955         The encrypted private key must be queued before the block hash
956         tree, since we need to know how large it is to know where the
957         block hash tree should go. The block hash tree must be put
958         before the share hash chain, since its size determines the
959         offset of the share hash chain.
960         """
961         assert self._offsets
962         assert "block_hash_tree" in self._offsets
963
964         assert isinstance(blockhashes, list)
965
966         blockhashes_s = "".join(blockhashes)
967         self._offsets['EOF'] = self._offsets['block_hash_tree'] + len(blockhashes_s)
968
969         self._writevs.append(tuple([self._offsets['block_hash_tree'],
970                                   blockhashes_s]))
971
972
973     def put_sharehashes(self, sharehashes):
974         """
975         I queue a write vector to put the share hash chain in my
976         argument onto the remote server.
977
978         The block hash tree must be queued before the share hash chain,
979         since we need to know where the block hash tree ends before we
980         can know where the share hash chain starts. The share hash chain
981         must be put before the signature, since the length of the packed
982         share hash chain determines the offset of the signature. Also,
983         semantically, you must know what the root of the block hash tree
984         is before you can generate a valid signature.
985         """
986         assert isinstance(sharehashes, dict)
987         assert self._offsets
988         if "share_hash_chain" not in self._offsets:
989             raise LayoutInvalid("You must put the block hash tree before "
990                                 "putting the share hash chain")
991
992         # The signature comes after the share hash chain. If the
993         # signature has already been written, we must not write another
994         # share hash chain. The signature writes the verification key
995         # offset when it gets sent to the remote server, so we look for
996         # that.
997         if "verification_key" in self._offsets:
998             raise LayoutInvalid("You must write the share hash chain "
999                                 "before you write the signature")
1000         sharehashes_s = "".join([struct.pack(">H32s", i, sharehashes[i])
1001                                   for i in sorted(sharehashes.keys())])
1002         self._offsets['signature'] = self._offsets['share_hash_chain'] + \
1003             len(sharehashes_s)
1004         self._writevs.append(tuple([self._offsets['share_hash_chain'],
1005                             sharehashes_s]))
1006
1007
1008     def put_root_hash(self, roothash):
1009         """
1010         Put the root hash (the root of the share hash tree) in the
1011         remote slot.
1012         """
1013         # It does not make sense to be able to put the root 
1014         # hash without first putting the share hashes, since you need
1015         # the share hashes to generate the root hash.
1016         #
1017         # Signature is defined by the routine that places the share hash
1018         # chain, so it's a good thing to look for in finding out whether
1019         # or not the share hash chain exists on the remote server.
1020         if len(roothash) != HASH_SIZE:
1021             raise LayoutInvalid("hashes and salts must be exactly %d bytes"
1022                                  % HASH_SIZE)
1023         self._root_hash = roothash
1024         # To write both of these values, we update the checkstring on
1025         # the remote server, which includes them
1026         checkstring = self.get_checkstring()
1027         self._writevs.append(tuple([0, checkstring]))
1028         # This write, if successful, changes the checkstring, so we need
1029         # to update our internal checkstring to be consistent with the
1030         # one on the server.
1031
1032
1033     def get_signable(self):
1034         """
1035         Get the first seven fields of the mutable file; the parts that
1036         are signed.
1037         """
1038         if not self._root_hash:
1039             raise LayoutInvalid("You need to set the root hash "
1040                                 "before getting something to "
1041                                 "sign")
1042         return struct.pack(MDMFSIGNABLEHEADER,
1043                            1,
1044                            self._seqnum,
1045                            self._root_hash,
1046                            self._required_shares,
1047                            self._total_shares,
1048                            self._segment_size,
1049                            self._data_length)
1050
1051
1052     def put_signature(self, signature):
1053         """
1054         I queue a write vector for the signature of the MDMF share.
1055
1056         I require that the root hash and share hash chain have been put
1057         to the grid before I will write the signature to the grid.
1058         """
1059         if "signature" not in self._offsets:
1060             raise LayoutInvalid("You must put the share hash chain "
1061         # It does not make sense to put a signature without first
1062         # putting the root hash and the salt hash (since otherwise
1063         # the signature would be incomplete), so we don't allow that.
1064                        "before putting the signature")
1065         if not self._root_hash:
1066             raise LayoutInvalid("You must complete the signed prefix "
1067                                 "before computing a signature")
1068         # If we put the signature after we put the verification key, we
1069         # could end up running into the verification key, and will
1070         # probably screw up the offsets as well. So we don't allow that.
1071         if "verification_key_end" in self._offsets:
1072             raise LayoutInvalid("You can't put the signature after the "
1073                                 "verification key")
1074         # The method that writes the verification key defines the EOF
1075         # offset before writing the verification key, so look for that.
1076         self._offsets['verification_key'] = self._offsets['signature'] +\
1077             len(signature)
1078         self._writevs.append(tuple([self._offsets['signature'], signature]))
1079
1080
1081     def put_verification_key(self, verification_key):
1082         """
1083         I queue a write vector for the verification key.
1084
1085         I require that the signature have been written to the storage
1086         server before I allow the verification key to be written to the
1087         remote server.
1088         """
1089         if "verification_key" not in self._offsets:
1090             raise LayoutInvalid("You must put the signature before you "
1091                                 "can put the verification key")
1092
1093         self._offsets['verification_key_end'] = \
1094             self._offsets['verification_key'] + len(verification_key)
1095         assert self._offsets['verification_key_end'] <= self._offsets['share_data']
1096         self._writevs.append(tuple([self._offsets['verification_key'],
1097                             verification_key]))
1098
1099
1100     def _get_offsets_tuple(self):
1101         return tuple([(key, value) for key, value in self._offsets.items()])
1102
1103
1104     def get_verinfo(self):
1105         return (self._seqnum,
1106                 self._root_hash,
1107                 self._required_shares,
1108                 self._total_shares,
1109                 self._segment_size,
1110                 self._data_length,
1111                 self.get_signable(),
1112                 self._get_offsets_tuple())
1113
1114
1115     def finish_publishing(self):
1116         """
1117         I add a write vector for the offsets table, and then cause all
1118         of the write vectors that I've dealt with so far to be published
1119         to the remote server, ending the write process.
1120         """
1121         if "verification_key_end" not in self._offsets:
1122             raise LayoutInvalid("You must put the verification key before "
1123                                 "you can publish the offsets")
1124         offsets_offset = struct.calcsize(MDMFHEADERWITHOUTOFFSETS)
1125         offsets = struct.pack(MDMFOFFSETS,
1126                               self._offsets['enc_privkey'],
1127                               self._offsets['share_hash_chain'],
1128                               self._offsets['signature'],
1129                               self._offsets['verification_key'],
1130                               self._offsets['verification_key_end'],
1131                               self._offsets['share_data'],
1132                               self._offsets['block_hash_tree'],
1133                               self._offsets['EOF'])
1134         self._writevs.append(tuple([offsets_offset, offsets]))
1135         encoding_parameters_offset = struct.calcsize(MDMFCHECKSTRING)
1136         params = struct.pack(">BBQQ",
1137                              self._required_shares,
1138                              self._total_shares,
1139                              self._segment_size,
1140                              self._data_length)
1141         self._writevs.append(tuple([encoding_parameters_offset, params]))
1142         return self._write(self._writevs)
1143
1144
1145     def _write(self, datavs, on_failure=None, on_success=None):
1146         """I write the data vectors in datavs to the remote slot."""
1147         tw_vectors = {}
1148         if not self._testvs:
1149             self._testvs = []
1150             self._testvs.append(tuple([0, 1, "eq", ""]))
1151         if not self._written:
1152             # Write a new checkstring to the share when we write it, so
1153             # that we have something to check later.
1154             new_checkstring = self.get_checkstring()
1155             datavs.append((0, new_checkstring))
1156             def _first_write():
1157                 self._written = True
1158                 self._testvs = [(0, len(new_checkstring), "eq", new_checkstring)]
1159             on_success = _first_write
1160         tw_vectors[self.shnum] = (self._testvs, datavs, None)
1161         d = self._rref.callRemote("slot_testv_and_readv_and_writev",
1162                                   self._storage_index,
1163                                   self._secrets,
1164                                   tw_vectors,
1165                                   self._readv)
1166         def _result(results):
1167             if isinstance(results, failure.Failure) or not results[0]:
1168                 # Do nothing; the write was unsuccessful.
1169                 if on_failure: on_failure()
1170             else:
1171                 if on_success: on_success()
1172             return results
1173         d.addCallback(_result)
1174         return d
1175
1176 def _handle_bad_struct(f):
1177     # struct.unpack errors mean the server didn't give us enough data, so
1178     # this share is bad
1179     f.trap(struct.error)
1180     raise BadShareError(f.value.args[0])
1181
1182 class MDMFSlotReadProxy:
1183     """
1184     I read from a mutable slot filled with data written in the MDMF data
1185     format (which is described above).
1186
1187     I can be initialized with some amount of data, which I will use (if
1188     it is valid) to eliminate some of the need to fetch it from servers.
1189     """
1190     def __init__(self,
1191                  rref,
1192                  storage_index,
1193                  shnum,
1194                  data=""):
1195         # Start the initialization process.
1196         self._rref = rref
1197         self._storage_index = storage_index
1198         self.shnum = shnum
1199
1200         # Before doing anything, the reader is probably going to want to
1201         # verify that the signature is correct. To do that, they'll need
1202         # the verification key, and the signature. To get those, we'll
1203         # need the offset table. So fetch the offset table on the
1204         # assumption that that will be the first thing that a reader is
1205         # going to do.
1206
1207         # The fact that these encoding parameters are None tells us
1208         # that we haven't yet fetched them from the remote share, so we
1209         # should. We could just not set them, but the checks will be
1210         # easier to read if we don't have to use hasattr.
1211         self._version_number = None
1212         self._sequence_number = None
1213         self._root_hash = None
1214         # Filled in if we're dealing with an SDMF file. Unused
1215         # otherwise.
1216         self._salt = None
1217         self._required_shares = None
1218         self._total_shares = None
1219         self._segment_size = None
1220         self._data_length = None
1221         self._offsets = None
1222
1223         # If the user has chosen to initialize us with some data, we'll
1224         # try to satisfy subsequent data requests with that data before
1225         # asking the storage server for it. If 
1226         self._data = data
1227         # The way callers interact with cache in the filenode returns
1228         # None if there isn't any cached data, but the way we index the
1229         # cached data requires a string, so convert None to "".
1230         if self._data == None:
1231             self._data = ""
1232
1233
1234     def _maybe_fetch_offsets_and_header(self, force_remote=False):
1235         """
1236         I fetch the offset table and the header from the remote slot if
1237         I don't already have them. If I do have them, I do nothing and
1238         return an empty Deferred.
1239         """
1240         if self._offsets:
1241             return defer.succeed(None)
1242         # At this point, we may be either SDMF or MDMF. Fetching 107 
1243         # bytes will be enough to get header and offsets for both SDMF and
1244         # MDMF, though we'll be left with 4 more bytes than we
1245         # need if this ends up being MDMF. This is probably less
1246         # expensive than the cost of a second roundtrip.
1247         readvs = [(0, 123)]
1248         d = self._read(readvs, force_remote)
1249         d.addCallback(self._process_encoding_parameters)
1250         d.addCallback(self._process_offsets)
1251         d.addErrback(_handle_bad_struct)
1252         return d
1253
1254
1255     def _process_encoding_parameters(self, encoding_parameters):
1256         if self.shnum not in encoding_parameters:
1257             raise BadShareError("no data for shnum %d" % self.shnum)
1258         encoding_parameters = encoding_parameters[self.shnum][0]
1259         # The first byte is the version number. It will tell us what
1260         # to do next.
1261         (verno,) = struct.unpack(">B", encoding_parameters[:1])
1262         if verno == MDMF_VERSION:
1263             read_size = MDMFHEADERWITHOUTOFFSETSSIZE
1264             (verno,
1265              seqnum,
1266              root_hash,
1267              k,
1268              n,
1269              segsize,
1270              datalen) = struct.unpack(MDMFHEADERWITHOUTOFFSETS,
1271                                       encoding_parameters[:read_size])
1272             if segsize == 0 and datalen == 0:
1273                 # Empty file, no segments.
1274                 self._num_segments = 0
1275             else:
1276                 self._num_segments = mathutil.div_ceil(datalen, segsize)
1277
1278         elif verno == SDMF_VERSION:
1279             read_size = SIGNED_PREFIX_LENGTH
1280             (verno,
1281              seqnum,
1282              root_hash,
1283              salt,
1284              k,
1285              n,
1286              segsize,
1287              datalen) = struct.unpack(">BQ32s16s BBQQ",
1288                                 encoding_parameters[:SIGNED_PREFIX_LENGTH])
1289             self._salt = salt
1290             if segsize == 0 and datalen == 0:
1291                 # empty file
1292                 self._num_segments = 0
1293             else:
1294                 # non-empty SDMF files have one segment.
1295                 self._num_segments = 1
1296         else:
1297             raise UnknownVersionError("You asked me to read mutable file "
1298                                       "version %d, but I only understand "
1299                                       "%d and %d" % (verno, SDMF_VERSION,
1300                                                      MDMF_VERSION))
1301
1302         self._version_number = verno
1303         self._sequence_number = seqnum
1304         self._root_hash = root_hash
1305         self._required_shares = k
1306         self._total_shares = n
1307         self._segment_size = segsize
1308         self._data_length = datalen
1309
1310         self._block_size = self._segment_size / self._required_shares
1311         # We can upload empty files, and need to account for this fact
1312         # so as to avoid zero-division and zero-modulo errors.
1313         if datalen > 0:
1314             tail_size = self._data_length % self._segment_size
1315         else:
1316             tail_size = 0
1317         if not tail_size:
1318             self._tail_block_size = self._block_size
1319         else:
1320             self._tail_block_size = mathutil.next_multiple(tail_size,
1321                                                     self._required_shares)
1322             self._tail_block_size /= self._required_shares
1323
1324         return encoding_parameters
1325
1326
1327     def _process_offsets(self, offsets):
1328         if self._version_number == 0:
1329             read_size = OFFSETS_LENGTH
1330             read_offset = SIGNED_PREFIX_LENGTH
1331             end = read_size + read_offset
1332             (signature,
1333              share_hash_chain,
1334              block_hash_tree,
1335              share_data,
1336              enc_privkey,
1337              EOF) = struct.unpack(">LLLLQQ",
1338                                   offsets[read_offset:end])
1339             self._offsets = {}
1340             self._offsets['signature'] = signature
1341             self._offsets['share_data'] = share_data
1342             self._offsets['block_hash_tree'] = block_hash_tree
1343             self._offsets['share_hash_chain'] = share_hash_chain
1344             self._offsets['enc_privkey'] = enc_privkey
1345             self._offsets['EOF'] = EOF
1346
1347         elif self._version_number == 1:
1348             read_offset = MDMFHEADERWITHOUTOFFSETSSIZE
1349             read_length = MDMFOFFSETS_LENGTH
1350             end = read_offset + read_length
1351             (encprivkey,
1352              sharehashes,
1353              signature,
1354              verification_key,
1355              verification_key_end,
1356              sharedata,
1357              blockhashes,
1358              eof) = struct.unpack(MDMFOFFSETS,
1359                                   offsets[read_offset:end])
1360             self._offsets = {}
1361             self._offsets['enc_privkey'] = encprivkey
1362             self._offsets['block_hash_tree'] = blockhashes
1363             self._offsets['share_hash_chain'] = sharehashes
1364             self._offsets['signature'] = signature
1365             self._offsets['verification_key'] = verification_key
1366             self._offsets['verification_key_end']= \
1367                 verification_key_end
1368             self._offsets['EOF'] = eof
1369             self._offsets['share_data'] = sharedata
1370
1371
1372     def get_block_and_salt(self, segnum):
1373         """
1374         I return (block, salt), where block is the block data and
1375         salt is the salt used to encrypt that segment.
1376         """
1377         d = self._maybe_fetch_offsets_and_header()
1378         def _then(ignored):
1379             base_share_offset = self._offsets['share_data']
1380
1381             if segnum + 1 > self._num_segments:
1382                 raise LayoutInvalid("Not a valid segment number")
1383
1384             if self._version_number == 0:
1385                 share_offset = base_share_offset + self._block_size * segnum
1386             else:
1387                 share_offset = base_share_offset + (self._block_size + \
1388                                                     SALT_SIZE) * segnum
1389             if segnum + 1 == self._num_segments:
1390                 data = self._tail_block_size
1391             else:
1392                 data = self._block_size
1393
1394             if self._version_number == 1:
1395                 data += SALT_SIZE
1396
1397             readvs = [(share_offset, data)]
1398             return readvs
1399         d.addCallback(_then)
1400         d.addCallback(lambda readvs: self._read(readvs))
1401         def _process_results(results):
1402             if self.shnum not in results:
1403                 raise BadShareError("no data for shnum %d" % self.shnum)
1404             if self._version_number == 0:
1405                 # We only read the share data, but we know the salt from
1406                 # when we fetched the header
1407                 data = results[self.shnum]
1408                 if not data:
1409                     data = ""
1410                 else:
1411                     if len(data) != 1:
1412                         raise BadShareError("got %d vectors, not 1" % len(data))
1413                     data = data[0]
1414                 salt = self._salt
1415             else:
1416                 data = results[self.shnum]
1417                 if not data:
1418                     salt = data = ""
1419                 else:
1420                     salt_and_data = results[self.shnum][0]
1421                     salt = salt_and_data[:SALT_SIZE]
1422                     data = salt_and_data[SALT_SIZE:]
1423             return data, salt
1424         d.addCallback(_process_results)
1425         return d
1426
1427
1428     def get_blockhashes(self, needed=None, force_remote=False):
1429         """
1430         I return the block hash tree
1431
1432         I take an optional argument, needed, which is a set of indices
1433         correspond to hashes that I should fetch. If this argument is
1434         missing, I will fetch the entire block hash tree; otherwise, I
1435         may attempt to fetch fewer hashes, based on what needed says
1436         that I should do. Note that I may fetch as many hashes as I
1437         want, so long as the set of hashes that I do fetch is a superset
1438         of the ones that I am asked for, so callers should be prepared
1439         to tolerate additional hashes.
1440         """
1441         # TODO: Return only the parts of the block hash tree necessary
1442         # to validate the blocknum provided?
1443         # This is a good idea, but it is hard to implement correctly. It
1444         # is bad to fetch any one block hash more than once, so we
1445         # probably just want to fetch the whole thing at once and then
1446         # serve it.
1447         if needed == set([]):
1448             return defer.succeed([])
1449         d = self._maybe_fetch_offsets_and_header()
1450         def _then(ignored):
1451             blockhashes_offset = self._offsets['block_hash_tree']
1452             if self._version_number == 1:
1453                 blockhashes_length = self._offsets['EOF'] - blockhashes_offset
1454             else:
1455                 blockhashes_length = self._offsets['share_data'] - blockhashes_offset
1456             readvs = [(blockhashes_offset, blockhashes_length)]
1457             return readvs
1458         d.addCallback(_then)
1459         d.addCallback(lambda readvs:
1460             self._read(readvs, force_remote=force_remote))
1461         def _build_block_hash_tree(results):
1462             if self.shnum not in results:
1463                 raise BadShareError("no data for shnum %d" % self.shnum)
1464
1465             rawhashes = results[self.shnum][0]
1466             results = [rawhashes[i:i+HASH_SIZE]
1467                        for i in range(0, len(rawhashes), HASH_SIZE)]
1468             return results
1469         d.addCallback(_build_block_hash_tree)
1470         return d
1471
1472
1473     def get_sharehashes(self, needed=None, force_remote=False):
1474         """
1475         I return the part of the share hash chain placed to validate
1476         this share.
1477
1478         I take an optional argument, needed. Needed is a set of indices
1479         that correspond to the hashes that I should fetch. If needed is
1480         not present, I will fetch and return the entire share hash
1481         chain. Otherwise, I may fetch and return any part of the share
1482         hash chain that is a superset of the part that I am asked to
1483         fetch. Callers should be prepared to deal with more hashes than
1484         they've asked for.
1485         """
1486         if needed == set([]):
1487             return defer.succeed([])
1488         d = self._maybe_fetch_offsets_and_header()
1489
1490         def _make_readvs(ignored):
1491             sharehashes_offset = self._offsets['share_hash_chain']
1492             if self._version_number == 0:
1493                 sharehashes_length = self._offsets['block_hash_tree'] - sharehashes_offset
1494             else:
1495                 sharehashes_length = self._offsets['signature'] - sharehashes_offset
1496             readvs = [(sharehashes_offset, sharehashes_length)]
1497             return readvs
1498         d.addCallback(_make_readvs)
1499         d.addCallback(lambda readvs:
1500             self._read(readvs, force_remote=force_remote))
1501         def _build_share_hash_chain(results):
1502             if self.shnum not in results:
1503                 raise BadShareError("no data for shnum %d" % self.shnum)
1504
1505             sharehashes = results[self.shnum][0]
1506             results = [sharehashes[i:i+(HASH_SIZE + 2)]
1507                        for i in range(0, len(sharehashes), HASH_SIZE + 2)]
1508             results = dict([struct.unpack(">H32s", data)
1509                             for data in results])
1510             return results
1511         d.addCallback(_build_share_hash_chain)
1512         d.addErrback(_handle_bad_struct)
1513         return d
1514
1515
1516     def get_encprivkey(self):
1517         """
1518         I return the encrypted private key.
1519         """
1520         d = self._maybe_fetch_offsets_and_header()
1521
1522         def _make_readvs(ignored):
1523             privkey_offset = self._offsets['enc_privkey']
1524             if self._version_number == 0:
1525                 privkey_length = self._offsets['EOF'] - privkey_offset
1526             else:
1527                 privkey_length = self._offsets['share_hash_chain'] - privkey_offset
1528             readvs = [(privkey_offset, privkey_length)]
1529             return readvs
1530         d.addCallback(_make_readvs)
1531         d.addCallback(lambda readvs: self._read(readvs))
1532         def _process_results(results):
1533             if self.shnum not in results:
1534                 raise BadShareError("no data for shnum %d" % self.shnum)
1535             privkey = results[self.shnum][0]
1536             return privkey
1537         d.addCallback(_process_results)
1538         return d
1539
1540
1541     def get_signature(self):
1542         """
1543         I return the signature of my share.
1544         """
1545         d = self._maybe_fetch_offsets_and_header()
1546
1547         def _make_readvs(ignored):
1548             signature_offset = self._offsets['signature']
1549             if self._version_number == 1:
1550                 signature_length = self._offsets['verification_key'] - signature_offset
1551             else:
1552                 signature_length = self._offsets['share_hash_chain'] - signature_offset
1553             readvs = [(signature_offset, signature_length)]
1554             return readvs
1555         d.addCallback(_make_readvs)
1556         d.addCallback(lambda readvs: self._read(readvs))
1557         def _process_results(results):
1558             if self.shnum not in results:
1559                 raise BadShareError("no data for shnum %d" % self.shnum)
1560             signature = results[self.shnum][0]
1561             return signature
1562         d.addCallback(_process_results)
1563         return d
1564
1565
1566     def get_verification_key(self):
1567         """
1568         I return the verification key.
1569         """
1570         d = self._maybe_fetch_offsets_and_header()
1571
1572         def _make_readvs(ignored):
1573             if self._version_number == 1:
1574                 vk_offset = self._offsets['verification_key']
1575                 vk_length = self._offsets['verification_key_end'] - vk_offset
1576             else:
1577                 vk_offset = struct.calcsize(">BQ32s16sBBQQLLLLQQ")
1578                 vk_length = self._offsets['signature'] - vk_offset
1579             readvs = [(vk_offset, vk_length)]
1580             return readvs
1581         d.addCallback(_make_readvs)
1582         d.addCallback(lambda readvs: self._read(readvs))
1583         def _process_results(results):
1584             if self.shnum not in results:
1585                 raise BadShareError("no data for shnum %d" % self.shnum)
1586             verification_key = results[self.shnum][0]
1587             return verification_key
1588         d.addCallback(_process_results)
1589         return d
1590
1591
1592     def get_encoding_parameters(self):
1593         """
1594         I return (k, n, segsize, datalen)
1595         """
1596         d = self._maybe_fetch_offsets_and_header()
1597         d.addCallback(lambda ignored:
1598             (self._required_shares,
1599              self._total_shares,
1600              self._segment_size,
1601              self._data_length))
1602         return d
1603
1604
1605     def get_seqnum(self):
1606         """
1607         I return the sequence number for this share.
1608         """
1609         d = self._maybe_fetch_offsets_and_header()
1610         d.addCallback(lambda ignored:
1611             self._sequence_number)
1612         return d
1613
1614
1615     def get_root_hash(self):
1616         """
1617         I return the root of the block hash tree
1618         """
1619         d = self._maybe_fetch_offsets_and_header()
1620         d.addCallback(lambda ignored: self._root_hash)
1621         return d
1622
1623
1624     def get_checkstring(self):
1625         """
1626         I return the packed representation of the following:
1627
1628             - version number
1629             - sequence number
1630             - root hash
1631             - salt hash
1632
1633         which my users use as a checkstring to detect other writers.
1634         """
1635         d = self._maybe_fetch_offsets_and_header()
1636         def _build_checkstring(ignored):
1637             if self._salt:
1638                 checkstring = struct.pack(PREFIX,
1639                                           self._version_number,
1640                                           self._sequence_number,
1641                                           self._root_hash,
1642                                           self._salt)
1643             else:
1644                 checkstring = struct.pack(MDMFCHECKSTRING,
1645                                           self._version_number,
1646                                           self._sequence_number,
1647                                           self._root_hash)
1648
1649             return checkstring
1650         d.addCallback(_build_checkstring)
1651         return d
1652
1653
1654     def get_prefix(self, force_remote):
1655         d = self._maybe_fetch_offsets_and_header(force_remote)
1656         d.addCallback(lambda ignored:
1657             self._build_prefix())
1658         return d
1659
1660
1661     def _build_prefix(self):
1662         # The prefix is another name for the part of the remote share
1663         # that gets signed. It consists of everything up to and
1664         # including the datalength, packed by struct.
1665         if self._version_number == SDMF_VERSION:
1666             return struct.pack(SIGNED_PREFIX,
1667                            self._version_number,
1668                            self._sequence_number,
1669                            self._root_hash,
1670                            self._salt,
1671                            self._required_shares,
1672                            self._total_shares,
1673                            self._segment_size,
1674                            self._data_length)
1675
1676         else:
1677             return struct.pack(MDMFSIGNABLEHEADER,
1678                            self._version_number,
1679                            self._sequence_number,
1680                            self._root_hash,
1681                            self._required_shares,
1682                            self._total_shares,
1683                            self._segment_size,
1684                            self._data_length)
1685
1686
1687     def _get_offsets_tuple(self):
1688         # The offsets tuple is another component of the version
1689         # information tuple. It is basically our offsets dictionary,
1690         # itemized and in a tuple.
1691         return self._offsets.copy()
1692
1693
1694     def get_verinfo(self):
1695         """
1696         I return my verinfo tuple. This is used by the ServermapUpdater
1697         to keep track of versions of mutable files.
1698
1699         The verinfo tuple for MDMF files contains:
1700             - seqnum
1701             - root hash
1702             - a blank (nothing)
1703             - segsize
1704             - datalen
1705             - k
1706             - n
1707             - prefix (the thing that you sign)
1708             - a tuple of offsets
1709
1710         We include the nonce in MDMF to simplify processing of version
1711         information tuples.
1712
1713         The verinfo tuple for SDMF files is the same, but contains a
1714         16-byte IV instead of a hash of salts.
1715         """
1716         d = self._maybe_fetch_offsets_and_header()
1717         def _build_verinfo(ignored):
1718             if self._version_number == SDMF_VERSION:
1719                 salt_to_use = self._salt
1720             else:
1721                 salt_to_use = None
1722             return (self._sequence_number,
1723                     self._root_hash,
1724                     salt_to_use,
1725                     self._segment_size,
1726                     self._data_length,
1727                     self._required_shares,
1728                     self._total_shares,
1729                     self._build_prefix(),
1730                     self._get_offsets_tuple())
1731         d.addCallback(_build_verinfo)
1732         return d
1733
1734
1735     def _read(self, readvs, force_remote=False):
1736         unsatisfiable = filter(lambda x: x[0] + x[1] > len(self._data), readvs)
1737         # TODO: It's entirely possible to tweak this so that it just
1738         # fulfills the requests that it can, and not demand that all
1739         # requests are satisfiable before running it.
1740         if not unsatisfiable and not force_remote:
1741             results = [self._data[offset:offset+length]
1742                        for (offset, length) in readvs]
1743             results = {self.shnum: results}
1744             return defer.succeed(results)
1745         else:
1746             return self._rref.callRemote("slot_readv",
1747                                          self._storage_index,
1748                                          [self.shnum],
1749                                          readvs)
1750
1751
1752     def is_sdmf(self):
1753         """I tell my caller whether or not my remote file is SDMF or MDMF
1754         """
1755         d = self._maybe_fetch_offsets_and_header()
1756         d.addCallback(lambda ignored:
1757             self._version_number == 0)
1758         return d
1759
1760
1761 class LayoutInvalid(BadShareError):
1762     """
1763     This isn't a valid MDMF mutable file
1764     """