5 * Created by Victor Grishchenko on 3/6/09.
6 * Copyright 2009 Delft University of Technology. All rights reserved.
11 //#include <openssl/sha.h>
22 const size_t Sha1Hash::SIZE = HASHSZ;
23 const Sha1Hash Sha1Hash::ZERO = Sha1Hash();
25 void SHA1 (const void *data, size_t length, unsigned char *hash) {
28 blk_SHA1_Update(&ctx, data, length);
29 blk_SHA1_Final(hash, &ctx);
32 Sha1Hash::Sha1Hash(const Sha1Hash& left, const Sha1Hash& right) {
34 memcpy(data,left.bits,SIZE);
35 memcpy(data+SIZE,right.bits,SIZE);
36 SHA1((unsigned char*)data,SIZE*2,bits);
39 Sha1Hash::Sha1Hash(const char* data, size_t length) {
41 length = strlen(data);
42 SHA1((unsigned char*)data,length,bits);
45 Sha1Hash::Sha1Hash(const uint8_t* data, size_t length) {
46 SHA1(data,length,bits);
49 Sha1Hash::Sha1Hash(bool hex, const char* hash) {
53 for(int i=0; i<SIZE; i++) {
54 strncpy(hx,hash+i*2,2);
55 sscanf(hx, "%x", &val);
58 assert(this->hex()==std::string(hash));
60 memcpy(bits,hash,SIZE);
63 std::string Sha1Hash::hex() const {
65 for(int i=0; i<HASHSZ; i++)
66 sprintf(hex+i*2, "%02x", (int)(unsigned char)bits[i]);
67 return std::string(hex,HASHSZ*2);
72 /** H a s h t r e e */
75 HashTree::HashTree (const char* filename, const Sha1Hash& root_hash, const char* hash_filename) :
76 root_hash_(root_hash), fd_(0), hash_fd_(0), data_recheck_(true),
77 peak_count_(0), hashes_(NULL), size_(0), sizek_(0),
78 complete_(0), completek_(0)
80 fd_ = open(filename,O_RDWR|O_CREAT,S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH);
85 strcat(hfn, filename);
86 strcat(hfn, ".mhash");
88 strcpy(hfn,hash_filename);
89 hash_fd_ = open(hfn,O_RDWR|O_CREAT,S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH);
92 if (root_hash_==Sha1Hash::ZERO) { // fresh submit, hash it
93 assert(file_size(fd_));
97 } // else LoadComplete()
101 void HashTree::Submit () {
102 size_ = file_size(fd_);
103 sizek_ = (size_>>10) + ((size_&1023) ? 1 : 0);
104 peak_count_ = bin64_t::peaks(sizek_,peaks_);
105 int hashes_size = Sha1Hash::SIZE*sizek_*2;
106 file_resize(hash_fd_,hashes_size);
107 hashes_ = (Sha1Hash*) memory_map(hash_fd_,hashes_size);
109 size_ = sizek_ = complete_ = completek_ = 0;
110 print_error("mmap failed");
113 for (size_t i=0; i<sizek_; i++) {
115 size_t rd = read(fd_,kilo,1<<10);
116 if (rd<(1<<10) && i!=sizek_-1) {
122 hashes_[pos] = Sha1Hash(kilo,rd);
127 for (int p=0; p<peak_count_; p++) {
128 if (!peaks_[p].is_base())
129 for(bin64_t b=peaks_[p].left_foot().parent(); b.within(peaks_[p]); b=b.next_dfsio(1))
130 hashes_[b] = Sha1Hash(hashes_[b.left()],hashes_[b.right()]);
131 peak_hashes_[p] = hashes_[peaks_[p]];
134 root_hash_ = DeriveRoot();
139 /** Basically, simulated receiving every single packet, except
140 for some optimizations. */
141 void HashTree::RecoverProgress () {
142 size_t size = file_size(fd_);
143 size_t sizek = (size>>10) + ((size&1023) ? 1 : 0);
145 int peak_count = bin64_t::peaks(sizek,peaks);
146 for(int i=0; i<peak_count; i++) {
148 file_seek(hash_fd_,peaks[i]*sizeof(Sha1Hash));
149 if (read(hash_fd_,&peak_hash,sizeof(Sha1Hash))!=sizeof(Sha1Hash))
151 OfferPeakHash(peaks[i], peak_hash);
154 return; // if no valid peak hashes found
155 // at this point, we may use mmapd hashes already
156 // so, lets verify hashes and the data we've got
158 memset(zeros, 0, 1<<10);
159 Sha1Hash kilo_zero(zeros,1<<10);
160 for(int p=0; p<packet_size(); p++) {
163 if (hashes_[pos]==Sha1Hash::ZERO)
165 size_t rd = read(fd_,buf,1<<10);
166 assert(rd==(1<<10) || p==packet_size()-1);
167 if (rd==(1<<10) && !memcmp(buf, zeros, rd) && hashes_[pos]!=kilo_zero)
169 if ( data_recheck_ && !OfferHash(pos, Sha1Hash(buf,rd)) )
178 bool HashTree::OfferPeakHash (bin64_t pos, const Sha1Hash& hash) {
181 bin64_t last_peak = peaks_[peak_count_-1];
182 if ( pos.layer()>=last_peak.layer() ||
183 pos.base_offset()!=last_peak.base_offset()+last_peak.width() )
186 peaks_[peak_count_] = pos;
187 peak_hashes_[peak_count_] = hash;
189 // check whether peak hash candidates add up to the root hash
190 Sha1Hash mustbe_root = DeriveRoot();
191 if (mustbe_root!=root_hash_)
193 for(int i=0; i<peak_count_; i++)
194 sizek_ += peaks_[i].width();
196 // bingo, we now know the file size (rounded up to a KByte)
199 completek_ = complete_ = 0;
200 sizek_ = (size_>>10) + ((size_&1023) ? 1 : 0);
202 size_t cur_size = file_size(fd_);
203 if ( cur_size<=(sizek_-1)<<10 || cur_size>sizek_<<10 )
204 if (file_resize(fd_, size_)) {
205 print_error("cannot set file size\n");
206 size_=0; // remain in the 0-state
210 // mmap the hash file into memory
211 size_t expected_size = sizeof(Sha1Hash)*sizek_*2;
212 if ( file_size(hash_fd_) != expected_size )
213 file_resize (hash_fd_, expected_size);
215 hashes_ = (Sha1Hash*) memory_map(hash_fd_,expected_size);
217 size_ = sizek_ = complete_ = completek_ = 0;
218 print_error("mmap failed");
222 for(int i=0; i<peak_count_; i++)
223 hashes_[peaks_[i]] = peak_hashes_[i];
228 Sha1Hash HashTree::DeriveRoot () {
229 int c = peak_count_-1;
230 bin64_t p = peaks_[c];
231 Sha1Hash hash = peak_hashes_[c];
233 while (p!=bin64_t::ALL) {
236 hash = Sha1Hash(hash,Sha1Hash::ZERO);
238 if (c<0 || peaks_[c]!=p.sibling())
239 return Sha1Hash::ZERO;
240 hash = Sha1Hash(peak_hashes_[c],hash);
244 //dprintf("p %lli %s\n",(uint64_t)p,hash.hex().c_str());
250 /** For live streaming: appends the data, adjusts the tree.
251 @ return the number of fresh (tail) peak hashes */
252 int HashTree::AppendData (char* data, int length) {
257 bin64_t HashTree::peak_for (bin64_t pos) const {
259 while (pi<peak_count_ && !pos.within(peaks_[pi]))
261 return pi==peak_count_ ? bin64_t(bin64_t::NONE) : peaks_[pi];
265 bool HashTree::OfferHash (bin64_t pos, const Sha1Hash& hash) {
266 if (!size_) // only peak hashes are accepted at this point
267 return OfferPeakHash(pos,hash);
268 bin64_t peak = peak_for(pos);
269 if (peak==bin64_t::NONE)
272 return hash == hashes_[pos];
273 if (ack_out_.get(pos.parent())!=bins::EMPTY)
274 return hash==hashes_[pos]; // have this hash already, even accptd data
277 return false; // who cares?
279 Sha1Hash uphash = hash;
280 while ( p!=peak && ack_out_.get(p)==bins::EMPTY ) {
283 uphash = Sha1Hash(hashes_[p.left()],hashes_[p.right()]) ;
284 }// walk to the nearest proven hash
285 return uphash==hashes_[p];
289 bool HashTree::OfferData (bin64_t pos, const char* data, size_t length) {
294 if (length<1024 && pos!=bin64_t(0,sizek_-1))
296 if (ack_out_.get(pos)==bins::FILLED)
297 return true; // to set data_in_
298 bin64_t peak = peak_for(pos);
299 if (peak==bin64_t::NONE)
302 if (!OfferHash(pos, Sha1Hash(data,length)))
305 //printf("g %lli %s\n",(uint64_t)pos,hash.hex().c_str());
306 ack_out_.set(pos,bins::FILLED);
307 pwrite(fd_,data,length,pos.base_offset()<<10);
310 if (pos.base_offset()==sizek_-1) {
311 size_ = ((sizek_-1)<<10) + length;
312 if (file_size(fd_)!=size_)
313 file_resize(fd_,size_);
319 uint64_t HashTree::seq_complete () {
320 uint64_t seqk = ack_out_.seq_length();
327 HashTree::~HashTree () {
329 memory_unmap(hash_fd_, hashes_, sizek_*2*sizeof(Sha1Hash));