5 * Created by Victor Grishchenko on 3/6/09.
6 * Copyright 2009 Delft University of Technology. All rights reserved.
11 //#include <openssl/sha.h>
19 #define OPENFLAGS O_RDWR|O_CREAT|_O_BINARY
21 #define OPENFLAGS O_RDWR|O_CREAT
25 using namespace swift;
28 const size_t Sha1Hash::SIZE = HASHSZ;
29 const Sha1Hash Sha1Hash::ZERO = Sha1Hash();
31 void SHA1 (const void *data, size_t length, unsigned char *hash) {
34 blk_SHA1_Update(&ctx, data, length);
35 blk_SHA1_Final(hash, &ctx);
38 Sha1Hash::Sha1Hash(const Sha1Hash& left, const Sha1Hash& right) {
40 memcpy(data,left.bits,SIZE);
41 memcpy(data+SIZE,right.bits,SIZE);
42 SHA1((unsigned char*)data,SIZE*2,bits);
45 Sha1Hash::Sha1Hash(const char* data, size_t length) {
47 length = strlen(data);
48 SHA1((unsigned char*)data,length,bits);
51 Sha1Hash::Sha1Hash(const uint8_t* data, size_t length) {
52 SHA1(data,length,bits);
55 Sha1Hash::Sha1Hash(bool hex, const char* hash) {
59 for(int i=0; i<SIZE; i++) {
60 strncpy(hx,hash+i*2,2);
61 if (sscanf(hx, "%x", &val)!=1) {
67 assert(this->hex()==std::string(hash));
69 memcpy(bits,hash,SIZE);
72 std::string Sha1Hash::hex() const {
74 for(int i=0; i<HASHSZ; i++)
75 sprintf(hex+i*2, "%02x", (int)(unsigned char)bits[i]);
76 return std::string(hex,HASHSZ*2);
81 /** H a s h t r e e */
84 HashTree::HashTree (const char* filename, const Sha1Hash& root_hash, const char* hash_filename) :
85 root_hash_(root_hash), fd_(0), hash_fd_(0), data_recheck_(true),
86 peak_count_(0), hashes_(NULL), size_(0), sizek_(0),
87 complete_(0), completek_(0)
89 fd_ = open(filename,OPENFLAGS,S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH);
92 print_error("cannot open the file");
97 strcat(hfn, filename);
98 strcat(hfn, ".mhash");
100 strcpy(hfn,hash_filename);
101 hash_fd_ = open(hfn,OPENFLAGS,S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH);
104 print_error("cannot open hash file");
107 if (root_hash_==Sha1Hash::ZERO) { // fresh submit, hash it
108 assert(file_size(fd_));
112 } // else LoadComplete()
116 void HashTree::Submit () {
117 size_ = file_size(fd_);
118 sizek_ = (size_ + 1023) >> 10;
119 peak_count_ = bin64_t::peaks(sizek_,peaks_);
120 int hashes_size = Sha1Hash::SIZE*sizek_*2;
121 file_resize(hash_fd_,hashes_size);
122 hashes_ = (Sha1Hash*) memory_map(hash_fd_,hashes_size);
124 size_ = sizek_ = complete_ = completek_ = 0;
125 print_error("mmap failed");
128 for (size_t i=0; i<sizek_; i++) {
130 size_t rd = read(fd_,kilo,1<<10);
131 if (rd<(1<<10) && i!=sizek_-1) {
137 hashes_[pos] = Sha1Hash(kilo,rd);
142 for (int p=0; p<peak_count_; p++) {
143 if (!peaks_[p].is_base())
144 for(bin64_t b=peaks_[p].left_foot().parent(); b.within(peaks_[p]); b=b.next_dfsio(1))
145 hashes_[b] = Sha1Hash(hashes_[b.left()],hashes_[b.right()]);
146 peak_hashes_[p] = hashes_[peaks_[p]];
149 root_hash_ = DeriveRoot();
154 /** Basically, simulated receiving every single packet, except
155 for some optimizations. */
156 void HashTree::RecoverProgress () {
157 size_t size = file_size(fd_);
158 size_t sizek = (size + 1023) >> 10;
160 int peak_count = bin64_t::peaks(sizek,peaks);
161 for(int i=0; i<peak_count; i++) {
163 file_seek(hash_fd_,peaks[i]*sizeof(Sha1Hash));
164 if (read(hash_fd_,&peak_hash,sizeof(Sha1Hash))!=sizeof(Sha1Hash))
166 OfferPeakHash(peaks[i], peak_hash);
169 return; // if no valid peak hashes found
170 // at this point, we may use mmapd hashes already
171 // so, lets verify hashes and the data we've got
173 memset(zeros, 0, 1<<10);
174 Sha1Hash kilo_zero(zeros,1<<10);
175 for(int p=0; p<packet_size(); p++) {
178 if (hashes_[pos]==Sha1Hash::ZERO)
180 size_t rd = read(fd_,buf,1<<10);
181 if (rd!=(1<<10) && p!=packet_size()-1)
183 if (rd==(1<<10) && !memcmp(buf, zeros, rd) &&
184 hashes_[pos]!=kilo_zero) // FIXME
186 if ( data_recheck_ && !OfferHash(pos, Sha1Hash(buf,rd)) )
191 if (rd!=(1<<10) && p==packet_size()-1)
192 size_ = ((sizek_-1)<<10) + rd;
197 bool HashTree::OfferPeakHash (bin64_t pos, const Sha1Hash& hash) {
200 bin64_t last_peak = peaks_[peak_count_-1];
201 if ( pos.layer()>=last_peak.layer() ||
202 pos.base_offset()!=last_peak.base_offset()+last_peak.width() )
205 peaks_[peak_count_] = pos;
206 peak_hashes_[peak_count_] = hash;
208 // check whether peak hash candidates add up to the root hash
209 Sha1Hash mustbe_root = DeriveRoot();
210 if (mustbe_root!=root_hash_)
212 for(int i=0; i<peak_count_; i++)
213 sizek_ += peaks_[i].width();
215 // bingo, we now know the file size (rounded up to a KByte)
218 completek_ = complete_ = 0;
219 sizek_ = (size_ + 1023) >> 10;
221 size_t cur_size = file_size(fd_);
222 if ( cur_size<=(sizek_-1)<<10 || cur_size>sizek_<<10 )
223 if (file_resize(fd_, size_)) {
224 print_error("cannot set file size\n");
225 size_=0; // remain in the 0-state
229 // mmap the hash file into memory
230 size_t expected_size = sizeof(Sha1Hash)*sizek_*2;
231 if ( file_size(hash_fd_) != expected_size )
232 file_resize (hash_fd_, expected_size);
234 hashes_ = (Sha1Hash*) memory_map(hash_fd_,expected_size);
236 size_ = sizek_ = complete_ = completek_ = 0;
237 print_error("mmap failed");
241 for(int i=0; i<peak_count_; i++)
242 hashes_[peaks_[i]] = peak_hashes_[i];
247 Sha1Hash HashTree::DeriveRoot () {
248 int c = peak_count_-1;
249 bin64_t p = peaks_[c];
250 Sha1Hash hash = peak_hashes_[c];
252 while (p!=bin64_t::ALL) {
255 hash = Sha1Hash(hash,Sha1Hash::ZERO);
257 if (c<0 || peaks_[c]!=p.sibling())
258 return Sha1Hash::ZERO;
259 hash = Sha1Hash(peak_hashes_[c],hash);
268 /** For live streaming: appends the data, adjusts the tree.
269 @ return the number of fresh (tail) peak hashes */
270 int HashTree::AppendData (char* data, int length) {
275 bin64_t HashTree::peak_for (bin64_t pos) const {
277 while (pi<peak_count_ && !pos.within(peaks_[pi]))
279 return pi==peak_count_ ? bin64_t(bin64_t::NONE) : peaks_[pi];
283 bool HashTree::OfferHash (bin64_t pos, const Sha1Hash& hash) {
284 if (!size_) // only peak hashes are accepted at this point
285 return OfferPeakHash(pos,hash);
286 bin64_t peak = peak_for(pos);
287 if (peak==bin64_t::NONE)
290 return hash == hashes_[pos];
291 if (ack_out_.get(pos.parent())!=binmap_t::EMPTY)
292 return hash==hashes_[pos]; // have this hash already, even accptd data
295 return false; // who cares?
297 Sha1Hash uphash = hash;
298 while ( p!=peak && ack_out_.get(p)==binmap_t::EMPTY ) {
301 uphash = Sha1Hash(hashes_[p.left()],hashes_[p.right()]) ;
302 }// walk to the nearest proven hash
303 return uphash==hashes_[p];
307 bool HashTree::OfferData (bin64_t pos, const char* data, size_t length) {
312 if (length<1024 && pos!=bin64_t(0,sizek_-1))
314 if (ack_out_.get(pos)==binmap_t::FILLED)
315 return true; // to set data_in_
316 bin64_t peak = peak_for(pos);
317 if (peak==bin64_t::NONE)
320 Sha1Hash data_hash(data,length);
321 if (!OfferHash(pos, data_hash)) {
322 //printf("invalid hash for %s: %s\n",pos.str(),data_hash.hex().c_str()); // paranoid
326 //printf("g %lli %s\n",(uint64_t)pos,hash.hex().c_str());
327 ack_out_.set(pos,binmap_t::FILLED);
328 pwrite(fd_,data,length,pos.base_offset()<<10);
331 if (pos.base_offset()==sizek_-1) {
332 size_ = ((sizek_-1)<<10) + length;
333 if (file_size(fd_)!=size_)
334 file_resize(fd_,size_);
340 uint64_t HashTree::seq_complete () {
341 uint64_t seqk = ack_out_.seq_length();
348 HashTree::~HashTree () {
350 memory_unmap(hash_fd_, hashes_, sizek_*2*sizeof(Sha1Hash));