Merge branch 'master' of git.irl.cs.ucla.edu:ndn/chronoshare
diff --git a/src/hash-string-converter.cc b/src/hash-string-converter.cc
new file mode 100644
index 0000000..2961069
--- /dev/null
+++ b/src/hash-string-converter.cc
@@ -0,0 +1,129 @@
+/* -*- Mode: C++; c-file-style: "gnu"; indent-tabs-mode:nil -*- */
+/*
+ * Copyright (c) 2012 University of California, Los Angeles
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License version 2 as
+ * published by the Free Software Foundation;
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ *
+ * Author: Alexander Afanasyev <alexander.afanasyev@ucla.edu>
+ *         Zhenkai Zhu <zhenkai@cs.ucla.edu>
+ */
+
+#include "hash-string-converter.h"
+
+#include <boost/assert.hpp>
+#include <boost/throw_exception.hpp>
+#include <boost/make_shared.hpp>
+#include <openssl/evp.h>
+
+typedef boost::error_info<struct tag_errmsg, std::string> errmsg_info_str; 
+typedef boost::error_info<struct tag_errmsg, int> errmsg_info_int; 
+
+#include <boost/archive/iterators/transform_width.hpp>
+#include <boost/iterator/transform_iterator.hpp>
+#include <boost/archive/iterators/dataflow_exception.hpp>
+
+using namespace boost;
+using namespace boost::archive::iterators;
+using namespace std;
+
+
+template<class CharType>
+struct hex_from_4_bit
+{
+  typedef CharType result_type;
+  CharType operator () (CharType ch) const
+  {
+    const char *lookup_table = "0123456789abcdef";
+    // cout << "New character: " << (int) ch << " (" << (char) ch << ")" << "\n";
+    BOOST_ASSERT (ch < 16);
+    return lookup_table[static_cast<size_t>(ch)];
+  }
+};
+
+typedef transform_iterator<hex_from_4_bit<string::const_iterator::value_type>,
+                           transform_width<string::const_iterator, 4, 8, string::const_iterator::value_type> > string_from_binary;
+
+
+template<class CharType>
+struct hex_to_4_bit
+{
+  typedef CharType result_type;
+  CharType operator () (CharType ch) const
+  {
+    const signed char lookup_table [] = {
+      -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
+      -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
+      -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
+      0, 1, 2, 3, 4, 5, 6, 7, 8, 9,-1,-1,-1,-1,-1,-1,
+      -1,10,11,12,13,14,15,-1,-1,-1,-1,-1,-1,-1,-1,-1,
+      -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
+      -1,10,11,12,13,14,15,-1,-1,-1,-1,-1,-1,-1,-1,-1,
+      -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1
+    };
+
+    // cout << "New character: " << hex << (int) ch << " (" << (char) ch << ")" << "\n";
+    signed char value = -1;
+    if ((unsigned)ch < 128)
+      value = lookup_table [(unsigned)ch];
+    if (value == -1)
+      BOOST_THROW_EXCEPTION (Error::HashConversion () << errmsg_info_int ((int)ch));
+    
+    return value;
+  }
+};
+
+typedef transform_width<transform_iterator<hex_to_4_bit<string::const_iterator::value_type>, string::const_iterator>, 8, 4> string_to_binary;
+
+
+std::ostream &
+operator << (std::ostream &os, const Hash &hash)
+{
+  if (hash.m_length == 0)
+    return os;
+
+  ostreambuf_iterator<char> out_it (os); // ostream iterator
+  // need to encode to base64
+  copy (string_from_binary (reinterpret_cast<const char*> (hash.m_buf)),
+        string_from_binary (reinterpret_cast<const char*> (hash.m_buf+hash.m_length)),
+        out_it);
+
+  return os;
+}
+
+Hash::Hash (const std::string &hashInTextEncoding)
+{
+  if (hashInTextEncoding.size () == 0)
+    {
+      m_buf = 0;
+      m_length = 0;
+      return;
+    }
+
+  if (hashInTextEncoding.size () > EVP_MAX_MD_SIZE * 2)
+    {
+      cerr << "Input hash is too long. Returning an empty hash" << endl;
+      m_buf = 0;
+      m_length = 0;
+      return;
+    }
+
+  m_buf = new unsigned char [EVP_MAX_MD_SIZE];
+  
+  unsigned char *end = copy (string_to_binary (hashInTextEncoding.begin ()),
+                            string_to_binary (hashInTextEncoding.end ()),
+                            m_buf);
+
+  m_length = end-m_buf;
+}
+
diff --git a/src/hash-string-converter.h b/src/hash-string-converter.h
new file mode 100644
index 0000000..b696426
--- /dev/null
+++ b/src/hash-string-converter.h
@@ -0,0 +1,100 @@
+/* -*- Mode: C++; c-file-style: "gnu"; indent-tabs-mode:nil -*- */
+/*
+ * Copyright (c) 2012 University of California, Los Angeles
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License version 2 as
+ * published by the Free Software Foundation;
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ *
+ * Author: Alexander Afanasyev <alexander.afanasyev@ucla.edu>
+ *         Zhenkai Zhu <zhenkai@cs.ucla.edu>
+ */
+
+#ifndef HASH_STRING_CONVERTER_H
+#define HASH_STRING_CONVERTER_H
+
+#include <string.h>
+#include <iostream>
+#include <boost/shared_ptr.hpp>
+#include <boost/exception/all.hpp>
+
+class Hash
+{
+public:
+  Hash (const void *buf, size_t length)
+    : m_length (length)
+  {
+    if (m_length != 0)
+      {
+        m_buf = new unsigned char [length];
+        memcpy (m_buf, buf, length);
+      }
+  }
+
+  Hash (const std::string &hashInTextEncoding);
+
+  ~Hash ()
+  {
+    if (m_length != 0)
+      delete [] m_buf;
+  }
+  
+  bool
+  IsZero () const
+  {
+    return m_length == 0 ||
+      (m_length == 1 && m_buf[0] == 0);
+  }
+
+  bool
+  operator == (const Hash &otherHash) const
+  {
+    if (m_length != otherHash.m_length)
+      return false;
+    
+    return memcmp (m_buf, otherHash.m_buf, m_length) == 0;
+  }
+
+  const void *
+  GetHash () const
+  {
+    return m_buf;
+  }
+
+  size_t
+  GetHashBytes () const
+  {
+    return m_length;
+  }
+  
+private:
+  unsigned char *m_buf;
+  size_t m_length;
+
+  Hash (const Hash &) { }
+  Hash & operator = (const Hash &) { return *this; }
+  
+  friend std::ostream &
+  operator << (std::ostream &os, const Hash &digest);
+};
+
+namespace Error {
+struct HashConversion : virtual boost::exception, virtual std::exception { };
+}
+
+typedef boost::shared_ptr<Hash> HashPtr;
+
+
+std::ostream &
+operator << (std::ostream &os, const Hash &digest);
+
+#endif // HASH_STRING_CONVERTER_H
diff --git a/src/main.cc b/src/main.cc
index f8338c4..82b5c7d 100644
--- a/src/main.cc
+++ b/src/main.cc
@@ -21,10 +21,61 @@
  */
 
 #include "sqlite-helper.h"
+#include <iostream>
+
+using namespace std;
+using namespace boost;
+
+typedef boost::error_info<struct tag_errmsg, std::string> errmsg_info_str; 
+
 
 int
 main (int argc, char **argv)
 {
-  DbHelper db ("./");
+  try
+    {
+      DbHelper db ("./");
+
+      HashPtr hash = db.RememberStateInStateLog ();
+      // should be empty
+      cout << "Hash: [" << *hash << "]" << endl;
+
+      //
+      db.UpdateDeviceSeqno ("Alex", 1);
+      hash = db.RememberStateInStateLog ();
+      cout << "Hash: [" << *hash << "]" << endl;
+
+      db.UpdateDeviceSeqno ("Alex", 2);
+      hash = db.RememberStateInStateLog ();
+      cout << "Hash: [" << *hash << "]" << endl;
+
+      db.UpdateDeviceSeqno ("Alex", 2);
+      hash = db.RememberStateInStateLog ();
+      cout << "Hash: [" << *hash << "]" << endl;
+
+      db.UpdateDeviceSeqno ("Alex", 1);
+      hash = db.RememberStateInStateLog ();
+      cout << "Hash: [" << *hash << "]" << endl;
+
+      db.FindStateDifferences ("00", "ec0a9941fa726e1fb8f34ecdbd8e3faa75dc9dba22e6a2ea1d8482aae5fdfb52");
+      db.FindStateDifferences ("ec0a9941fa726e1fb8f34ecdbd8e3faa75dc9dba22e6a2ea1d8482aae5fdfb52", "00");
+      db.FindStateDifferences ("869c38c6dffe8911ced320aecc6d9244904d13d3e8cd21081311f2129b4557ce",
+                               "ec0a9941fa726e1fb8f34ecdbd8e3faa75dc9dba22e6a2ea1d8482aae5fdfb52");
+      db.FindStateDifferences ("ec0a9941fa726e1fb8f34ecdbd8e3faa75dc9dba22e6a2ea1d8482aae5fdfb52",
+                               "869c38c6dffe8911ced320aecc6d9244904d13d3e8cd21081311f2129b4557ce");
+
+      db.UpdateDeviceSeqno ("Bob", 1);
+      hash = db.RememberStateInStateLog ();
+      cout << "Hash: [" << *hash << "]" << endl;
+
+      db.FindStateDifferences ("00", "48f4d95b503b9a79c2d5939fa67722b13fc01db861fc501d09efd0a38dbafab8");
+      db.FindStateDifferences ("ec0a9941fa726e1fb8f34ecdbd8e3faa75dc9dba22e6a2ea1d8482aae5fdfb52",
+                               "48f4d95b503b9a79c2d5939fa67722b13fc01db861fc501d09efd0a38dbafab8");
+    }
+  catch (const boost::exception &e)
+    {
+      cout << "ERRORR: " << *get_error_info<errmsg_info_str> (e) << endl;
+    }
+
   return 0;
 }
diff --git a/src/sqlite-helper.cc b/src/sqlite-helper.cc
index c9c508b..1a3ed1c 100644
--- a/src/sqlite-helper.cc
+++ b/src/sqlite-helper.cc
@@ -21,6 +21,8 @@
 
 #include "sqlite-helper.h"
 // #include "sync-log.h"
+#include <boost/make_shared.hpp>
+#include <boost/ref.hpp>
 
 // Other options: VP_md2, EVP_md5, EVP_sha, EVP_sha1, EVP_sha256, EVP_dss, EVP_dss1, EVP_mdc2, EVP_ripemd160
 #define HASH_FUNCTION EVP_sha256
@@ -29,8 +31,11 @@
 typedef boost::error_info<struct tag_errmsg, std::string> errmsg_info_str; 
 // typedef boost::error_info<struct tag_errmsg, int> errmsg_info_int; 
 
+using namespace boost;
 
 const std::string INIT_DATABASE = "\
+PRAGMA foreign_keys = ON;                                       \
+                                                                \
 CREATE TABLE                                                    \
     SyncNodes(                                                  \
         device_id       INTEGER PRIMARY KEY AUTOINCREMENT,      \
@@ -41,26 +46,41 @@
         last_update     TIMESTAMP                               \
     );                                                          \
                                                                 \
-CREATE INDEX SyncNodes_device_name ON SyncNodes (device_name);  \
-                                                                \
-CREATE TABLE SyncLog(                                           \
-        state_hash  BLOB NOT NULL PRIMARY KEY,                  \
-        last_update TIMESTAMP NOT NULL                          \
-    );                                                          \
-                                                                \
-CREATE TABLE                                                    \
-    SyncStateNodes(                                             \
-        id          INTEGER PRIMARY KEY AUTOINCREMENT,          \
-        state_hash  BLOB NOT NULL                                       \
-            REFERENCES SyncLog (state_hash) ON UPDATE CASCADE ON DELETE CASCADE, \
+CREATE TRIGGER SyncNodesUpdater_trigger                                \
+    BEFORE INSERT ON SyncNodes                                         \
+    FOR EACH ROW                                                       \
+    WHEN (SELECT device_id                                             \
+             FROM SyncNodes                                            \
+             WHERE device_name=NEW.device_name)                        \
+         IS NOT NULL                                                   \
+    BEGIN                                                              \
+        UPDATE SyncNodes                                               \
+            SET seq_no=max(seq_no,NEW.seq_no)                          \
+            WHERE device_name=NEW.device_name;                         \
+        SELECT RAISE(IGNORE);                                          \
+    END;                                                               \
+                                                                       \
+CREATE INDEX SyncNodes_device_name ON SyncNodes (device_name);         \
+                                                                       \
+CREATE TABLE SyncLog(                                                  \
+        state_id    INTEGER PRIMARY KEY AUTOINCREMENT,                 \
+        state_hash  BLOB NOT NULL UNIQUE,                              \
+        last_update TIMESTAMP NOT NULL                                 \
+    );                                                                 \
+                                                                       \
+CREATE TABLE                                                            \
+    SyncStateNodes(                                                     \
+        id          INTEGER PRIMARY KEY AUTOINCREMENT,                  \
+        state_id    INTEGER NOT NULL                                    \
+            REFERENCES SyncLog (state_id) ON UPDATE CASCADE ON DELETE CASCADE, \
         device_id   INTEGER NOT NULL                                    \
             REFERENCES SyncNodes (device_id) ON UPDATE CASCADE ON DELETE CASCADE, \
         seq_no      INTEGER NOT NULL                                    \
     );                                                                  \
                                                                         \
 CREATE INDEX SyncStateNodes_device_id ON SyncStateNodes (device_id);    \
-CREATE INDEX SyncStateNodes_state_hash ON SyncStateNodes (state_hash);  \
-CREATE INDEX SyncStateNodes_seq_no ON SyncStateNodes (seq_no);          \
+CREATE INDEX SyncStateNodes_state_id  ON SyncStateNodes (state_id);  \
+CREATE INDEX SyncStateNodes_seq_no    ON SyncStateNodes (seq_no);          \
                                                                         \
 CREATE TRIGGER SyncLogGuard_trigger                                     \
     BEFORE INSERT ON SyncLog                                            \
@@ -84,26 +104,36 @@
     }
   
   res = sqlite3_create_function (m_db, "hash", 2, SQLITE_ANY, 0, 0,
-                                     DbHelper::hash_xStep, DbHelper::hash_xFinal);
+                                 DbHelper::hash_xStep, DbHelper::hash_xFinal);
   if (res != SQLITE_OK)
     {
       BOOST_THROW_EXCEPTION (Error::Db ()
                              << errmsg_info_str ("Cannot create function ``hash''"));
     }
 
+  res = sqlite3_create_function (m_db, "hash2str", 2, SQLITE_ANY, 0,
+                                 DbHelper::hash2str_Func,
+                                 0, 0);
+  if (res != SQLITE_OK)
+    {
+      BOOST_THROW_EXCEPTION (Error::Db ()
+                             << errmsg_info_str ("Cannot create function ``hash''"));
+    }
+
+  res = sqlite3_create_function (m_db, "str2hash", 2, SQLITE_ANY, 0,
+                                 DbHelper::str2hash_Func,
+                                 0, 0);
+  if (res != SQLITE_OK)
+    {
+      BOOST_THROW_EXCEPTION (Error::Db ()
+                             << errmsg_info_str ("Cannot create function ``hash''"));
+    }
+  
   // Alex: determine if tables initialized. if not, initialize... not sure what is the best way to go...
   // for now, just attempt to create everything
 
   char *errmsg = 0;
   res = sqlite3_exec (m_db, INIT_DATABASE.c_str (), NULL, NULL, &errmsg);
-  // if (res != SQLITE_OK && errmsg != 0)
-  //   {
-  //     std::cerr << "DEBUG: " << errmsg << std::endl;
-  //     sqlite3_free (errmsg);
-  //   }
-
-  res = sqlite3_exec (m_db, "INSERT INTO SyncLog (state_hash, last_update) SELECT hash(device_name, seq_no), datetime('now') FROM SyncNodes ORDER BY device_name",
-                          NULL, NULL, &errmsg);
   if (res != SQLITE_OK && errmsg != 0)
     {
       std::cerr << "DEBUG: " << errmsg << std::endl;
@@ -120,6 +150,72 @@
     }
 }
 
+HashPtr
+DbHelper::RememberStateInStateLog ()
+{
+  int res = sqlite3_exec (m_db, "BEGIN TRANSACTION;", 0,0,0);
+
+  res += sqlite3_exec (m_db, "\
+INSERT INTO SyncLog                                     \
+    (state_hash, last_update)                           \
+    SELECT                                              \
+       hash(device_name, seq_no), datetime('now')       \
+    FROM SyncNodes                                      \
+    ORDER BY device_name;                               \
+", 0,0,0);
+
+  if (res != SQLITE_OK)
+    {
+      BOOST_THROW_EXCEPTION (Error::Db ()
+                             << errmsg_info_str ("1"));
+    }
+  
+  sqlite3_int64 rowId = sqlite3_last_insert_rowid (m_db);
+  
+  sqlite3_stmt *insertStmt;
+  res += sqlite3_prepare (m_db, "\
+INSERT INTO SyncStateNodes                              \
+      (state_id, device_id, seq_no)                     \
+      SELECT ?, device_id, seq_no                       \
+            FROM SyncNodes;                             \
+", -1, &insertStmt, 0);
+
+  res += sqlite3_bind_int64 (insertStmt, 1, rowId);
+  sqlite3_step (insertStmt);
+
+  if (res != SQLITE_OK)
+    {
+      BOOST_THROW_EXCEPTION (Error::Db ()
+                             << errmsg_info_str ("4"));
+    }
+  sqlite3_finalize (insertStmt);
+  
+  sqlite3_stmt *getHashStmt;
+  res += sqlite3_prepare (m_db, "\
+SELECT state_hash FROM SyncLog WHERE state_id = ?\
+", -1, &getHashStmt, 0);
+  res += sqlite3_bind_int64 (getHashStmt, 1, rowId);
+
+  HashPtr retval;
+  int stepRes = sqlite3_step (getHashStmt);
+  if (stepRes == SQLITE_ROW)
+    {
+      retval = make_shared<Hash> (sqlite3_column_blob (getHashStmt, 0),
+                                  sqlite3_column_bytes (getHashStmt, 0));
+    }
+  sqlite3_finalize (getHashStmt);
+  res += sqlite3_exec (m_db, "COMMIT;", 0,0,0);
+
+  if (res != SQLITE_OK)
+    {
+      BOOST_THROW_EXCEPTION (Error::Db ()
+                             << errmsg_info_str ("Some error with rememberStateInStateLog"));
+    }
+
+  return retval;
+}
+
+
 void
 DbHelper::hash_xStep (sqlite3_context *context, int argc, sqlite3_value **argv)
 {
@@ -172,7 +268,8 @@
 
   if (*hash_context == 0) // no rows
     {
-      sqlite3_result_null (context);
+      char charNullResult = 0;
+      sqlite3_result_blob (context, &charNullResult, 1, SQLITE_TRANSIENT); //SQLITE_TRANSIENT forces to make a copy
       return;
     }
   
@@ -187,3 +284,170 @@
   
   EVP_MD_CTX_destroy (*hash_context);
 }
+
+void
+DbHelper::hash2str_Func (sqlite3_context *context, int argc, sqlite3_value **argv)
+{
+  if (argc != 1 || sqlite3_value_type (argv[0]) != SQLITE_BLOB)
+    {
+      sqlite3_result_error (context, "Wrong arguments are supplied for ``hash2str'' function", -1);
+      return;
+    }
+
+  int hashBytes = sqlite3_value_bytes (argv[0]);
+  const void *hash = sqlite3_value_blob (argv[0]);
+
+  std::ostringstream os;
+  Hash tmpHash (hash, hashBytes);
+  os << tmpHash;
+  sqlite3_result_text (context, os.str ().c_str (), -1, SQLITE_TRANSIENT);
+}
+
+void
+DbHelper::str2hash_Func (sqlite3_context *context, int argc, sqlite3_value **argv)
+{
+  if (argc != 1 || sqlite3_value_type (argv[0]) != SQLITE_TEXT)
+    {
+      sqlite3_result_error (context, "Wrong arguments are supplied for ``str2hash'' function", -1);
+      return;
+    }
+
+  size_t hashTextBytes = sqlite3_value_bytes (argv[0]);
+  const unsigned char *hashText = sqlite3_value_text (argv[0]);
+
+  Hash hash (std::string (reinterpret_cast<const char*> (hashText), hashTextBytes));
+  sqlite3_result_blob (context, hash.GetHash (), hash.GetHashBytes (), SQLITE_TRANSIENT);
+}
+
+
+sqlite3_int64
+DbHelper::LookupSyncLog (const std::string &stateHash)
+{
+  Hash tmpHash (stateHash);
+  return LookupSyncLog (stateHash);
+}
+
+sqlite3_int64
+DbHelper::LookupSyncLog (const Hash &stateHash)
+{
+  sqlite3_stmt *stmt;
+  int res = sqlite3_prepare (m_db, "SELECT state_id FROM SyncLog WHERE state_hash = ?",
+                             -1, &stmt, 0);
+  
+  if (res != SQLITE_OK)
+    {
+      BOOST_THROW_EXCEPTION (Error::Db ()
+                             << errmsg_info_str ("Cannot prepare statement"));
+    }
+
+  res = sqlite3_bind_blob (stmt, 1, stateHash.GetHash (), stateHash.GetHashBytes (), SQLITE_STATIC);
+  if (res != SQLITE_OK)
+    {
+      BOOST_THROW_EXCEPTION (Error::Db ()
+                             << errmsg_info_str ("Cannot bind"));
+    }
+
+  sqlite3_int64 row = 0; // something bad
+
+  if (sqlite3_step (stmt) == SQLITE_ROW)
+    {
+      row = sqlite3_column_int64 (stmt, 0);
+    }
+
+  sqlite3_finalize (stmt);
+
+  return row;
+}
+
+void
+DbHelper::UpdateDeviceSeqno (const std::string &name, uint64_t seqNo)
+{
+  sqlite3_stmt *stmt;
+  // update is performed using trigger
+  int res = sqlite3_prepare (m_db, "INSERT INTO SyncNodes (device_name, seq_no) VALUES (?,?);", 
+                             -1, &stmt, 0);
+
+  res += sqlite3_bind_text  (stmt, 1, name.c_str (), name.size (), SQLITE_STATIC);
+  res += sqlite3_bind_int64 (stmt, 2, seqNo);
+  sqlite3_step (stmt);
+  
+  if (res != SQLITE_OK)
+    {
+      BOOST_THROW_EXCEPTION (Error::Db ()
+                             << errmsg_info_str ("Some error with UpdateDeviceSeqno"));
+    }
+  sqlite3_finalize (stmt);
+}
+
+void
+DbHelper::FindStateDifferences (const std::string &oldHash, const std::string &newHash)
+{
+  Hash tmpOldHash (oldHash);
+  Hash tmpNewHash (newHash);
+
+  FindStateDifferences (tmpOldHash, tmpNewHash);
+}
+
+void
+DbHelper::FindStateDifferences (const Hash &oldHash, const Hash &newHash)
+{
+  sqlite3_stmt *stmt;
+
+  int res = sqlite3_prepare_v2 (m_db, "\
+SELECT sn.device_name, s_old.seq_no, s_new.seq_no                       \
+    FROM (SELECT *                                                      \
+            FROM SyncStateNodes                                         \
+            WHERE state_id=(SELECT state_id                             \
+                                FROM SyncLog                            \
+                                WHERE state_hash=:old_hash)) s_old      \
+    LEFT JOIN (SELECT *                                                 \
+                FROM SyncStateNodes                                     \
+                WHERE state_id=(SELECT state_id                         \
+                                    FROM SyncLog                        \
+                                    WHERE state_hash=:new_hash)) s_new  \
+                                                                        \
+        ON s_old.device_id = s_new.device_id                            \
+    JOIN SyncNodes sn ON sn.device_id = s_old.device_id                 \
+                                                                        \
+    WHERE s_new.seq_no IS NULL OR                                       \
+          s_old.seq_no != s_new.seq_no                                  \
+                                                                        \
+UNION ALL                                                               \
+                                                                        \
+SELECT sn.device_name, s_old.seq_no, s_new.seq_no                       \
+    FROM (SELECT *                                                      \
+            FROM SyncStateNodes                                         \
+            WHERE state_id=(SELECT state_id                             \
+                                FROM SyncLog                            \
+                                WHERE state_hash=:new_hash )) s_new     \
+    LEFT JOIN (SELECT *                                                 \
+                FROM SyncStateNodes                                     \
+                WHERE state_id=(SELECT state_id                         \
+                                    FROM SyncLog                        \
+                                    WHERE state_hash=:old_hash)) s_old  \
+                                                                        \
+        ON s_old.device_id = s_new.device_id                            \
+    JOIN SyncNodes sn ON sn.device_id = s_new.device_id                 \
+                                                                        \
+    WHERE s_old.seq_no IS NULL                                          \
+", -1, &stmt, 0);
+
+  if (res != SQLITE_OK)
+    {
+      BOOST_THROW_EXCEPTION (Error::Db ()
+                             << errmsg_info_str ("Some error with FindStateDifferences"));
+    }
+
+  res += sqlite3_bind_blob  (stmt, 1, oldHash.GetHash (), oldHash.GetHashBytes (), SQLITE_STATIC);
+  res += sqlite3_bind_blob  (stmt, 2, newHash.GetHash (), newHash.GetHashBytes (), SQLITE_STATIC);
+
+  while (sqlite3_step (stmt) == SQLITE_ROW)
+    {
+      std::cout << sqlite3_column_text (stmt, 0) <<
+        ": from "  << sqlite3_column_int64 (stmt, 1) <<
+        " to "     << sqlite3_column_int64 (stmt, 2) <<
+        std::endl;
+    }
+  sqlite3_finalize (stmt);
+  
+}
diff --git a/src/sqlite-helper.h b/src/sqlite-helper.h
index 6874259..e119523 100644
--- a/src/sqlite-helper.h
+++ b/src/sqlite-helper.h
@@ -26,6 +26,7 @@
 #include <openssl/evp.h>
 #include <boost/exception/all.hpp>
 #include <string>
+#include "hash-string-converter.h"
 
 // temporarily ignoring all potential database errors
 
@@ -35,14 +36,50 @@
   DbHelper (const std::string &path);
   ~DbHelper ();
 
-  
+  // done
+  void
+  UpdateDeviceSeqno (const std::string &name, uint64_t seqNo);
+
+  // std::string
+  // LookupForwardingAlias (const std::string &deviceName);
+
+  // void
+  // UpdateForwardingAlias ();
+
+  // done
+  /**
+   * Create an entry in SyncLog and SyncStateNodes corresponding to the current state of SyncNodes
+   */
+  HashPtr
+  RememberStateInStateLog ();
+
+  // done
+  sqlite3_int64
+  LookupSyncLog (const std::string &stateHash);
+
+  // done
+  sqlite3_int64
+  LookupSyncLog (const Hash &stateHash);
+
+  // How difference is exposed will be determined later by the actual protocol
+  void
+  FindStateDifferences (const std::string &oldHash, const std::string &newHash);
+
+  void
+  FindStateDifferences (const Hash &oldHash, const Hash &newHash);
   
 private:
   static void
-  hash_xStep (sqlite3_context*,int,sqlite3_value**);
+  hash_xStep (sqlite3_context *context, int argc, sqlite3_value **argv);
 
   static void
-  hash_xFinal (sqlite3_context*);
+  hash_xFinal (sqlite3_context *context);
+
+  static void
+  hash2str_Func (sqlite3_context *context, int argc, sqlite3_value **argv);
+
+  static void
+  str2hash_Func (sqlite3_context *context, int argc, sqlite3_value **argv);
   
 private:
   sqlite3 *m_db;
diff --git a/wscript b/wscript
index ede09a8..a4da7d8 100644
--- a/wscript
+++ b/wscript
@@ -81,7 +81,9 @@
         target="tmp",
         features=['cxx', 'cxxprogram'],
         # source = bld.path.ant_glob(['src/**/*.cc']),
-        source = ['src/main.cc', 'src/sqlite-helper.cc'],
+        source = ['src/main.cc', 
+                  'src/sqlite-helper.cc',
+                  'src/hash-string-converter.cc'],
         use = 'BOOST BOOST_IOSTREAMS BOOST_REGEX CCNX SSL SQLITE3',
         includes = ['include', 'src'],
         )