Code modernization: src/p*, src/q*, src/r*, src/s* (partial) (#6282)
[oweals/minetest.git] / src / rollback.cpp
1 /*
2 Minetest
3 Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
4
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 of the License, or
8 (at your option) any later version.
9
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 GNU Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 */
19
20 #include "rollback.h"
21 #include <fstream>
22 #include <list>
23 #include <sstream>
24 #include "log.h"
25 #include "mapnode.h"
26 #include "gamedef.h"
27 #include "nodedef.h"
28 #include "util/serialize.h"
29 #include "util/string.h"
30 #include "util/numeric.h"
31 #include "inventorymanager.h" // deserializing InventoryLocations
32 #include "sqlite3.h"
33 #include "filesys.h"
34
35 #define POINTS_PER_NODE (16.0)
36
37 #define SQLRES(f, good) \
38         if ((f) != (good)) {\
39                 throw FileNotGoodException(std::string("RollbackManager: " \
40                         "SQLite3 error (" __FILE__ ":" TOSTRING(__LINE__) \
41                         "): ") + sqlite3_errmsg(db)); \
42         }
43 #define SQLOK(f) SQLRES(f, SQLITE_OK)
44
45 #define SQLOK_ERRSTREAM(s, m)                             \
46         if ((s) != SQLITE_OK) {                               \
47                 errorstream << "RollbackManager: " << (m) << ": " \
48                         << sqlite3_errmsg(db) << std::endl;           \
49         }
50
51 #define FINALIZE_STATEMENT(statement) \
52         SQLOK_ERRSTREAM(sqlite3_finalize(statement), "Failed to finalize " #statement)
53
54 class ItemStackRow : public ItemStack {
55 public:
56         ItemStackRow & operator = (const ItemStack & other)
57         {
58                 *static_cast<ItemStack *>(this) = other;
59                 return *this;
60         }
61
62         int id;
63 };
64
65 struct ActionRow {
66         int          id;
67         int          actor;
68         time_t       timestamp;
69         int          type;
70         std::string  location, list;
71         int          index, add;
72         ItemStackRow stack;
73         int          nodeMeta;
74         int          x, y, z;
75         int          oldNode;
76         int          oldParam1, oldParam2;
77         std::string  oldMeta;
78         int          newNode;
79         int          newParam1, newParam2;
80         std::string  newMeta;
81         int          guessed;
82 };
83
84
85 struct Entity {
86         int         id;
87         std::string name;
88 };
89
90
91
92 RollbackManager::RollbackManager(const std::string & world_path,
93                 IGameDef * gamedef_) :
94         gamedef(gamedef_)
95 {
96         verbosestream << "RollbackManager::RollbackManager(" << world_path
97                 << ")" << std::endl;
98
99         std::string txt_filename = world_path + DIR_DELIM "rollback.txt";
100         std::string migrating_flag = txt_filename + ".migrating";
101         database_path = world_path + DIR_DELIM "rollback.sqlite";
102
103         bool created = initDatabase();
104
105         if (fs::PathExists(txt_filename) && (created ||
106                         fs::PathExists(migrating_flag))) {
107                 std::ofstream of(migrating_flag.c_str());
108                 of.close();
109                 migrate(txt_filename);
110                 fs::DeleteSingleFileOrEmptyDirectory(migrating_flag);
111         }
112 }
113
114
115 RollbackManager::~RollbackManager()
116 {
117         flush();
118
119         FINALIZE_STATEMENT(stmt_insert);
120         FINALIZE_STATEMENT(stmt_replace);
121         FINALIZE_STATEMENT(stmt_select);
122         FINALIZE_STATEMENT(stmt_select_range);
123         FINALIZE_STATEMENT(stmt_select_withActor);
124         FINALIZE_STATEMENT(stmt_knownActor_select);
125         FINALIZE_STATEMENT(stmt_knownActor_insert);
126         FINALIZE_STATEMENT(stmt_knownNode_select);
127         FINALIZE_STATEMENT(stmt_knownNode_insert);
128
129         SQLOK_ERRSTREAM(sqlite3_close(db), "Could not close db");
130 }
131
132
133 void RollbackManager::registerNewActor(const int id, const std::string &name)
134 {
135         Entity actor = {id, name};
136         knownActors.push_back(actor);
137 }
138
139
140 void RollbackManager::registerNewNode(const int id, const std::string &name)
141 {
142         Entity node = {id, name};
143         knownNodes.push_back(node);
144 }
145
146
147 int RollbackManager::getActorId(const std::string &name)
148 {
149         for (std::vector<Entity>::const_iterator iter = knownActors.begin();
150                         iter != knownActors.end(); ++iter) {
151                 if (iter->name == name) {
152                         return iter->id;
153                 }
154         }
155
156         SQLOK(sqlite3_bind_text(stmt_knownActor_insert, 1, name.c_str(), name.size(), NULL));
157         SQLRES(sqlite3_step(stmt_knownActor_insert), SQLITE_DONE);
158         SQLOK(sqlite3_reset(stmt_knownActor_insert));
159
160         int id = sqlite3_last_insert_rowid(db);
161         registerNewActor(id, name);
162
163         return id;
164 }
165
166
167 int RollbackManager::getNodeId(const std::string &name)
168 {
169         for (std::vector<Entity>::const_iterator iter = knownNodes.begin();
170                         iter != knownNodes.end(); ++iter) {
171                 if (iter->name == name) {
172                         return iter->id;
173                 }
174         }
175
176         SQLOK(sqlite3_bind_text(stmt_knownNode_insert, 1, name.c_str(), name.size(), NULL));
177         SQLRES(sqlite3_step(stmt_knownNode_insert), SQLITE_DONE);
178         SQLOK(sqlite3_reset(stmt_knownNode_insert));
179
180         int id = sqlite3_last_insert_rowid(db);
181         registerNewNode(id, name);
182
183         return id;
184 }
185
186
187 const char * RollbackManager::getActorName(const int id)
188 {
189         for (std::vector<Entity>::const_iterator iter = knownActors.begin();
190                         iter != knownActors.end(); ++iter) {
191                 if (iter->id == id) {
192                         return iter->name.c_str();
193                 }
194         }
195
196         return "";
197 }
198
199
200 const char * RollbackManager::getNodeName(const int id)
201 {
202         for (std::vector<Entity>::const_iterator iter = knownNodes.begin();
203                         iter != knownNodes.end(); ++iter) {
204                 if (iter->id == id) {
205                         return iter->name.c_str();
206                 }
207         }
208
209         return "";
210 }
211
212
213 bool RollbackManager::createTables()
214 {
215         SQLOK(sqlite3_exec(db,
216                 "CREATE TABLE IF NOT EXISTS `actor` (\n"
217                 "       `id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,\n"
218                 "       `name` TEXT NOT NULL\n"
219                 ");\n"
220                 "CREATE TABLE IF NOT EXISTS `node` (\n"
221                 "       `id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,\n"
222                 "       `name` TEXT NOT NULL\n"
223                 ");\n"
224                 "CREATE TABLE IF NOT EXISTS `action` (\n"
225                 "       `id` INTEGER PRIMARY KEY AUTOINCREMENT,\n"
226                 "       `actor` INTEGER NOT NULL,\n"
227                 "       `timestamp` TIMESTAMP NOT NULL,\n"
228                 "       `type` INTEGER NOT NULL,\n"
229                 "       `list` TEXT,\n"
230                 "       `index` INTEGER,\n"
231                 "       `add` INTEGER,\n"
232                 "       `stackNode` INTEGER,\n"
233                 "       `stackQuantity` INTEGER,\n"
234                 "       `nodeMeta` INTEGER,\n"
235                 "       `x` INT,\n"
236                 "       `y` INT,\n"
237                 "       `z` INT,\n"
238                 "       `oldNode` INTEGER,\n"
239                 "       `oldParam1` INTEGER,\n"
240                 "       `oldParam2` INTEGER,\n"
241                 "       `oldMeta` TEXT,\n"
242                 "       `newNode` INTEGER,\n"
243                 "       `newParam1` INTEGER,\n"
244                 "       `newParam2` INTEGER,\n"
245                 "       `newMeta` TEXT,\n"
246                 "       `guessedActor` INTEGER,\n"
247                 "       FOREIGN KEY (`actor`) REFERENCES `actor`(`id`),\n"
248                 "       FOREIGN KEY (`stackNode`) REFERENCES `node`(`id`),\n"
249                 "       FOREIGN KEY (`oldNode`)   REFERENCES `node`(`id`),\n"
250                 "       FOREIGN KEY (`newNode`)   REFERENCES `node`(`id`)\n"
251                 ");\n"
252                 "CREATE INDEX IF NOT EXISTS `actionIndex` ON `action`(`x`,`y`,`z`,`timestamp`,`actor`);\n",
253                 NULL, NULL, NULL));
254         verbosestream << "SQL Rollback: SQLite3 database structure was created" << std::endl;
255
256         return true;
257 }
258
259
260 bool RollbackManager::initDatabase()
261 {
262         verbosestream << "RollbackManager: Database connection setup" << std::endl;
263
264         bool needs_create = !fs::PathExists(database_path);
265         SQLOK(sqlite3_open_v2(database_path.c_str(), &db,
266                         SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, NULL));
267
268         if (needs_create) {
269                 createTables();
270         }
271
272         SQLOK(sqlite3_prepare_v2(db,
273                 "INSERT INTO `action` (\n"
274                 "       `actor`, `timestamp`, `type`,\n"
275                 "       `list`, `index`, `add`, `stackNode`, `stackQuantity`, `nodeMeta`,\n"
276                 "       `x`, `y`, `z`,\n"
277                 "       `oldNode`, `oldParam1`, `oldParam2`, `oldMeta`,\n"
278                 "       `newNode`, `newParam1`, `newParam2`, `newMeta`,\n"
279                 "       `guessedActor`\n"
280                 ") VALUES (\n"
281                 "       ?, ?, ?,\n"
282                 "       ?, ?, ?, ?, ?, ?,\n"
283                 "       ?, ?, ?,\n"
284                 "       ?, ?, ?, ?,\n"
285                 "       ?, ?, ?, ?,\n"
286                 "       ?"
287                 ");",
288                 -1, &stmt_insert, NULL));
289
290         SQLOK(sqlite3_prepare_v2(db,
291                 "REPLACE INTO `action` (\n"
292                 "       `actor`, `timestamp`, `type`,\n"
293                 "       `list`, `index`, `add`, `stackNode`, `stackQuantity`, `nodeMeta`,\n"
294                 "       `x`, `y`, `z`,\n"
295                 "       `oldNode`, `oldParam1`, `oldParam2`, `oldMeta`,\n"
296                 "       `newNode`, `newParam1`, `newParam2`, `newMeta`,\n"
297                 "       `guessedActor`, `id`\n"
298                 ") VALUES (\n"
299                 "       ?, ?, ?,\n"
300                 "       ?, ?, ?, ?, ?, ?,\n"
301                 "       ?, ?, ?,\n"
302                 "       ?, ?, ?, ?,\n"
303                 "       ?, ?, ?, ?,\n"
304                 "       ?, ?\n"
305                 ");",
306                 -1, &stmt_replace, NULL));
307
308         SQLOK(sqlite3_prepare_v2(db,
309                 "SELECT\n"
310                 "       `actor`, `timestamp`, `type`,\n"
311                 "       `list`, `index`, `add`, `stackNode`, `stackQuantity`, `nodemeta`,\n"
312                 "       `x`, `y`, `z`,\n"
313                 "       `oldNode`, `oldParam1`, `oldParam2`, `oldMeta`,\n"
314                 "       `newNode`, `newParam1`, `newParam2`, `newMeta`,\n"
315                 "       `guessedActor`\n"
316                 " FROM `action`\n"
317                 " WHERE `timestamp` >= ?\n"
318                 " ORDER BY `timestamp` DESC, `id` DESC",
319                 -1, &stmt_select, NULL));
320
321         SQLOK(sqlite3_prepare_v2(db,
322                 "SELECT\n"
323                 "       `actor`, `timestamp`, `type`,\n"
324                 "       `list`, `index`, `add`, `stackNode`, `stackQuantity`, `nodemeta`,\n"
325                 "       `x`, `y`, `z`,\n"
326                 "       `oldNode`, `oldParam1`, `oldParam2`, `oldMeta`,\n"
327                 "       `newNode`, `newParam1`, `newParam2`, `newMeta`,\n"
328                 "       `guessedActor`\n"
329                 "FROM `action`\n"
330                 "WHERE `timestamp` >= ?\n"
331                 "       AND `x` IS NOT NULL\n"
332                 "       AND `y` IS NOT NULL\n"
333                 "       AND `z` IS NOT NULL\n"
334                 "       AND `x` BETWEEN ? AND ?\n"
335                 "       AND `y` BETWEEN ? AND ?\n"
336                 "       AND `z` BETWEEN ? AND ?\n"
337                 "ORDER BY `timestamp` DESC, `id` DESC\n"
338                 "LIMIT 0,?",
339                 -1, &stmt_select_range, NULL));
340
341         SQLOK(sqlite3_prepare_v2(db,
342                 "SELECT\n"
343                 "       `actor`, `timestamp`, `type`,\n"
344                 "       `list`, `index`, `add`, `stackNode`, `stackQuantity`, `nodemeta`,\n"
345                 "       `x`, `y`, `z`,\n"
346                 "       `oldNode`, `oldParam1`, `oldParam2`, `oldMeta`,\n"
347                 "       `newNode`, `newParam1`, `newParam2`, `newMeta`,\n"
348                 "       `guessedActor`\n"
349                 "FROM `action`\n"
350                 "WHERE `timestamp` >= ?\n"
351                 "       AND `actor` = ?\n"
352                 "ORDER BY `timestamp` DESC, `id` DESC\n",
353                 -1, &stmt_select_withActor, NULL));
354
355         SQLOK(sqlite3_prepare_v2(db, "SELECT `id`, `name` FROM `actor`",
356                         -1, &stmt_knownActor_select, NULL));
357
358         SQLOK(sqlite3_prepare_v2(db, "INSERT INTO `actor` (`name`) VALUES (?)",
359                         -1, &stmt_knownActor_insert, NULL));
360
361         SQLOK(sqlite3_prepare_v2(db, "SELECT `id`, `name` FROM `node`",
362                         -1, &stmt_knownNode_select, NULL));
363
364         SQLOK(sqlite3_prepare_v2(db, "INSERT INTO `node` (`name`) VALUES (?)",
365                         -1, &stmt_knownNode_insert, NULL));
366
367         verbosestream << "SQL prepared statements setup correctly" << std::endl;
368
369         while (sqlite3_step(stmt_knownActor_select) == SQLITE_ROW) {
370                 registerNewActor(
371                         sqlite3_column_int(stmt_knownActor_select, 0),
372                         reinterpret_cast<const char *>(sqlite3_column_text(stmt_knownActor_select, 1))
373                 );
374         }
375         SQLOK(sqlite3_reset(stmt_knownActor_select));
376
377         while (sqlite3_step(stmt_knownNode_select) == SQLITE_ROW) {
378                 registerNewNode(
379                         sqlite3_column_int(stmt_knownNode_select, 0),
380                         reinterpret_cast<const char *>(sqlite3_column_text(stmt_knownNode_select, 1))
381                 );
382         }
383         SQLOK(sqlite3_reset(stmt_knownNode_select));
384
385         return needs_create;
386 }
387
388
389 bool RollbackManager::registerRow(const ActionRow & row)
390 {
391         sqlite3_stmt * stmt_do = (row.id) ? stmt_replace : stmt_insert;
392
393         bool nodeMeta = false;
394
395         SQLOK(sqlite3_bind_int  (stmt_do, 1, row.actor));
396         SQLOK(sqlite3_bind_int64(stmt_do, 2, row.timestamp));
397         SQLOK(sqlite3_bind_int  (stmt_do, 3, row.type));
398
399         if (row.type == RollbackAction::TYPE_MODIFY_INVENTORY_STACK) {
400                 const std::string & loc = row.location;
401                 nodeMeta = (loc.substr(0, 9) == "nodemeta:");
402
403                 SQLOK(sqlite3_bind_text(stmt_do, 4, row.list.c_str(), row.list.size(), NULL));
404                 SQLOK(sqlite3_bind_int (stmt_do, 5, row.index));
405                 SQLOK(sqlite3_bind_int (stmt_do, 6, row.add));
406                 SQLOK(sqlite3_bind_int (stmt_do, 7, row.stack.id));
407                 SQLOK(sqlite3_bind_int (stmt_do, 8, row.stack.count));
408                 SQLOK(sqlite3_bind_int (stmt_do, 9, (int) nodeMeta));
409
410                 if (nodeMeta) {
411                         std::string::size_type p1, p2;
412                         p1 = loc.find(':') + 1;
413                         p2 = loc.find(',');
414                         std::string x = loc.substr(p1, p2 - p1);
415                         p1 = p2 + 1;
416                         p2 = loc.find(',', p1);
417                         std::string y = loc.substr(p1, p2 - p1);
418                         std::string z = loc.substr(p2 + 1);
419                         SQLOK(sqlite3_bind_int(stmt_do, 10, atoi(x.c_str())));
420                         SQLOK(sqlite3_bind_int(stmt_do, 11, atoi(y.c_str())));
421                         SQLOK(sqlite3_bind_int(stmt_do, 12, atoi(z.c_str())));
422                 }
423         } else {
424                 SQLOK(sqlite3_bind_null(stmt_do, 4));
425                 SQLOK(sqlite3_bind_null(stmt_do, 5));
426                 SQLOK(sqlite3_bind_null(stmt_do, 6));
427                 SQLOK(sqlite3_bind_null(stmt_do, 7));
428                 SQLOK(sqlite3_bind_null(stmt_do, 8));
429                 SQLOK(sqlite3_bind_null(stmt_do, 9));
430         }
431
432         if (row.type == RollbackAction::TYPE_SET_NODE) {
433                 SQLOK(sqlite3_bind_int (stmt_do, 10, row.x));
434                 SQLOK(sqlite3_bind_int (stmt_do, 11, row.y));
435                 SQLOK(sqlite3_bind_int (stmt_do, 12, row.z));
436                 SQLOK(sqlite3_bind_int (stmt_do, 13, row.oldNode));
437                 SQLOK(sqlite3_bind_int (stmt_do, 14, row.oldParam1));
438                 SQLOK(sqlite3_bind_int (stmt_do, 15, row.oldParam2));
439                 SQLOK(sqlite3_bind_text(stmt_do, 16, row.oldMeta.c_str(), row.oldMeta.size(), NULL));
440                 SQLOK(sqlite3_bind_int (stmt_do, 17, row.newNode));
441                 SQLOK(sqlite3_bind_int (stmt_do, 18, row.newParam1));
442                 SQLOK(sqlite3_bind_int (stmt_do, 19, row.newParam2));
443                 SQLOK(sqlite3_bind_text(stmt_do, 20, row.newMeta.c_str(), row.newMeta.size(), NULL));
444                 SQLOK(sqlite3_bind_int (stmt_do, 21, row.guessed ? 1 : 0));
445         } else {
446                 if (!nodeMeta) {
447                         SQLOK(sqlite3_bind_null(stmt_do, 10));
448                         SQLOK(sqlite3_bind_null(stmt_do, 11));
449                         SQLOK(sqlite3_bind_null(stmt_do, 12));
450                 }
451                 SQLOK(sqlite3_bind_null(stmt_do, 13));
452                 SQLOK(sqlite3_bind_null(stmt_do, 14));
453                 SQLOK(sqlite3_bind_null(stmt_do, 15));
454                 SQLOK(sqlite3_bind_null(stmt_do, 16));
455                 SQLOK(sqlite3_bind_null(stmt_do, 17));
456                 SQLOK(sqlite3_bind_null(stmt_do, 18));
457                 SQLOK(sqlite3_bind_null(stmt_do, 19));
458                 SQLOK(sqlite3_bind_null(stmt_do, 20));
459                 SQLOK(sqlite3_bind_null(stmt_do, 21));
460         }
461
462         if (row.id) {
463                 SQLOK(sqlite3_bind_int(stmt_do, 22, row.id));
464         }
465
466         int written = sqlite3_step(stmt_do);
467
468         SQLOK(sqlite3_reset(stmt_do));
469
470         return written == SQLITE_DONE;
471 }
472
473
474 const std::list<ActionRow> RollbackManager::actionRowsFromSelect(sqlite3_stmt* stmt)
475 {
476         std::list<ActionRow> rows;
477         const unsigned char * text;
478         size_t size;
479
480         while (sqlite3_step(stmt) == SQLITE_ROW) {
481                 ActionRow row;
482
483                 row.actor     = sqlite3_column_int  (stmt, 0);
484                 row.timestamp = sqlite3_column_int64(stmt, 1);
485                 row.type      = sqlite3_column_int  (stmt, 2);
486
487                 if (row.type == RollbackAction::TYPE_MODIFY_INVENTORY_STACK) {
488                         text = sqlite3_column_text (stmt, 3);
489                         size = sqlite3_column_bytes(stmt, 3);
490                         row.list        = std::string(reinterpret_cast<const char*>(text), size);
491                         row.index       = sqlite3_column_int(stmt, 4);
492                         row.add         = sqlite3_column_int(stmt, 5);
493                         row.stack.id    = sqlite3_column_int(stmt, 6);
494                         row.stack.count = sqlite3_column_int(stmt, 7);
495                         row.nodeMeta    = sqlite3_column_int(stmt, 8);
496                 }
497
498                 if (row.type == RollbackAction::TYPE_SET_NODE || row.nodeMeta) {
499                         row.x = sqlite3_column_int(stmt,  9);
500                         row.y = sqlite3_column_int(stmt, 10);
501                         row.z = sqlite3_column_int(stmt, 11);
502                 }
503
504                 if (row.type == RollbackAction::TYPE_SET_NODE) {
505                         row.oldNode   = sqlite3_column_int(stmt, 12);
506                         row.oldParam1 = sqlite3_column_int(stmt, 13);
507                         row.oldParam2 = sqlite3_column_int(stmt, 14);
508                         text = sqlite3_column_text (stmt, 15);
509                         size = sqlite3_column_bytes(stmt, 15);
510                         row.oldMeta   = std::string(reinterpret_cast<const char*>(text), size);
511                         row.newNode   = sqlite3_column_int(stmt, 16);
512                         row.newParam1 = sqlite3_column_int(stmt, 17);
513                         row.newParam2 = sqlite3_column_int(stmt, 18);
514                         text = sqlite3_column_text(stmt, 19);
515                         size = sqlite3_column_bytes(stmt, 19);
516                         row.newMeta   = std::string(reinterpret_cast<const char*>(text), size);
517                         row.guessed   = sqlite3_column_int(stmt, 20);
518                 }
519
520                 if (row.nodeMeta) {
521                         row.location = "nodemeta:";
522                         row.location += itos(row.x);
523                         row.location += ',';
524                         row.location += itos(row.y);
525                         row.location += ',';
526                         row.location += itos(row.z);
527                 } else {
528                         row.location = getActorName(row.actor);
529                 }
530
531                 rows.push_back(row);
532         }
533
534         SQLOK(sqlite3_reset(stmt));
535
536         return rows;
537 }
538
539
540 ActionRow RollbackManager::actionRowFromRollbackAction(const RollbackAction & action)
541 {
542         ActionRow row;
543
544         row.id        = 0;
545         row.actor     = getActorId(action.actor);
546         row.timestamp = action.unix_time;
547         row.type      = action.type;
548
549         if (row.type == RollbackAction::TYPE_MODIFY_INVENTORY_STACK) {
550                 row.location = action.inventory_location;
551                 row.list     = action.inventory_list;
552                 row.index    = action.inventory_index;
553                 row.add      = action.inventory_add;
554                 row.stack    = action.inventory_stack;
555                 row.stack.id = getNodeId(row.stack.name);
556         } else {
557                 row.x         = action.p.X;
558                 row.y         = action.p.Y;
559                 row.z         = action.p.Z;
560                 row.oldNode   = getNodeId(action.n_old.name);
561                 row.oldParam1 = action.n_old.param1;
562                 row.oldParam2 = action.n_old.param2;
563                 row.oldMeta   = action.n_old.meta;
564                 row.newNode   = getNodeId(action.n_new.name);
565                 row.newParam1 = action.n_new.param1;
566                 row.newParam2 = action.n_new.param2;
567                 row.newMeta   = action.n_new.meta;
568                 row.guessed   = action.actor_is_guess;
569         }
570
571         return row;
572 }
573
574
575 const std::list<RollbackAction> RollbackManager::rollbackActionsFromActionRows(
576                 const std::list<ActionRow> & rows)
577 {
578         std::list<RollbackAction> actions;
579
580         for (const ActionRow &row : rows) {
581                 RollbackAction action;
582                 action.actor     = (row.actor) ? getActorName(row.actor) : "";
583                 action.unix_time = row.timestamp;
584                 action.type      = static_cast<RollbackAction::Type>(row.type);
585
586                 switch (action.type) {
587                 case RollbackAction::TYPE_MODIFY_INVENTORY_STACK:
588                         action.inventory_location = row.location;
589                         action.inventory_list     = row.list;
590                         action.inventory_index    = row.index;
591                         action.inventory_add      = row.add;
592                         action.inventory_stack    = row.stack;
593                         if (action.inventory_stack.name.empty()) {
594                                 action.inventory_stack.name = getNodeName(row.stack.id);
595                         }
596                         break;
597
598                 case RollbackAction::TYPE_SET_NODE:
599                         action.p            = v3s16(row.x, row.y, row.z);
600                         action.n_old.name   = getNodeName(row.oldNode);
601                         action.n_old.param1 = row.oldParam1;
602                         action.n_old.param2 = row.oldParam2;
603                         action.n_old.meta   = row.oldMeta;
604                         action.n_new.name   = getNodeName(row.newNode);
605                         action.n_new.param1 = row.newParam1;
606                         action.n_new.param2 = row.newParam2;
607                         action.n_new.meta   = row.newMeta;
608                         break;
609
610                 default:
611                         throw ("W.T.F.");
612                         break;
613                 }
614
615                 actions.push_back(action);
616         }
617
618         return actions;
619 }
620
621
622 const std::list<ActionRow> RollbackManager::getRowsSince(time_t firstTime, const std::string & actor)
623 {
624         sqlite3_stmt *stmt_stmt = actor.empty() ? stmt_select : stmt_select_withActor;
625         sqlite3_bind_int64(stmt_stmt, 1, firstTime);
626
627         if (!actor.empty()) {
628                 sqlite3_bind_int(stmt_stmt, 2, getActorId(actor));
629         }
630
631         const std::list<ActionRow> & rows = actionRowsFromSelect(stmt_stmt);
632         sqlite3_reset(stmt_stmt);
633
634         return rows;
635 }
636
637
638 const std::list<ActionRow> RollbackManager::getRowsSince_range(
639                 time_t start_time, v3s16 p, int range, int limit)
640 {
641
642         sqlite3_bind_int64(stmt_select_range, 1, start_time);
643         sqlite3_bind_int  (stmt_select_range, 2, static_cast<int>(p.X - range));
644         sqlite3_bind_int  (stmt_select_range, 3, static_cast<int>(p.X + range));
645         sqlite3_bind_int  (stmt_select_range, 4, static_cast<int>(p.Y - range));
646         sqlite3_bind_int  (stmt_select_range, 5, static_cast<int>(p.Y + range));
647         sqlite3_bind_int  (stmt_select_range, 6, static_cast<int>(p.Z - range));
648         sqlite3_bind_int  (stmt_select_range, 7, static_cast<int>(p.Z + range));
649         sqlite3_bind_int  (stmt_select_range, 8, limit);
650
651         const std::list<ActionRow> & rows = actionRowsFromSelect(stmt_select_range);
652         sqlite3_reset(stmt_select_range);
653
654         return rows;
655 }
656
657
658 const std::list<RollbackAction> RollbackManager::getActionsSince_range(
659                 time_t start_time, v3s16 p, int range, int limit)
660 {
661         return rollbackActionsFromActionRows(getRowsSince_range(start_time, p, range, limit));
662 }
663
664
665 const std::list<RollbackAction> RollbackManager::getActionsSince(
666                 time_t start_time, const std::string & actor)
667 {
668         return rollbackActionsFromActionRows(getRowsSince(start_time, actor));
669 }
670
671
672 void RollbackManager::migrate(const std::string & file_path)
673 {
674         std::cout << "Migrating from rollback.txt to rollback.sqlite." << std::endl;
675
676         std::ifstream fh(file_path.c_str(), std::ios::in | std::ios::ate);
677         if (!fh.good()) {
678                 throw FileNotGoodException("Unable to open rollback.txt");
679         }
680
681         std::streampos file_size = fh.tellg();
682
683         if (file_size < 10) {
684                 errorstream << "Empty rollback log." << std::endl;
685                 return;
686         }
687
688         fh.seekg(0);
689
690         sqlite3_stmt *stmt_begin;
691         sqlite3_stmt *stmt_commit;
692         SQLOK(sqlite3_prepare_v2(db, "BEGIN", -1, &stmt_begin, NULL));
693         SQLOK(sqlite3_prepare_v2(db, "COMMIT", -1, &stmt_commit, NULL));
694
695         std::string bit;
696         int i = 0;
697         time_t start = time(0);
698         time_t t = start;
699         SQLRES(sqlite3_step(stmt_begin), SQLITE_DONE);
700         sqlite3_reset(stmt_begin);
701         do {
702                 ActionRow row;
703                 row.id = 0;
704
705                 // Get the timestamp
706                 std::getline(fh, bit, ' ');
707                 bit = trim(bit);
708                 if (!atoi(bit.c_str())) {
709                         std::getline(fh, bit);
710                         continue;
711                 }
712                 row.timestamp = atoi(bit.c_str());
713
714                 // Get the actor
715                 row.actor = getActorId(deSerializeJsonString(fh));
716
717                 // Get the action type
718                 std::getline(fh, bit, '[');
719                 std::getline(fh, bit, ' ');
720
721                 if (bit == "modify_inventory_stack") {
722                         row.type = RollbackAction::TYPE_MODIFY_INVENTORY_STACK;
723                         row.location = trim(deSerializeJsonString(fh));
724                         std::getline(fh, bit, ' ');
725                         row.list     = trim(deSerializeJsonString(fh));
726                         std::getline(fh, bit, ' ');
727                         std::getline(fh, bit, ' ');
728                         row.index    = atoi(trim(bit).c_str());
729                         std::getline(fh, bit, ' ');
730                         row.add      = (int)(trim(bit) == "add");
731                         row.stack.deSerialize(deSerializeJsonString(fh));
732                         row.stack.id = getNodeId(row.stack.name);
733                         std::getline(fh, bit);
734                 } else if (bit == "set_node") {
735                         row.type = RollbackAction::TYPE_SET_NODE;
736                         std::getline(fh, bit, '(');
737                         std::getline(fh, bit, ',');
738                         row.x       = atoi(trim(bit).c_str());
739                         std::getline(fh, bit, ',');
740                         row.y       = atoi(trim(bit).c_str());
741                         std::getline(fh, bit, ')');
742                         row.z       = atoi(trim(bit).c_str());
743                         std::getline(fh, bit, ' ');
744                         row.oldNode = getNodeId(trim(deSerializeJsonString(fh)));
745                         std::getline(fh, bit, ' ');
746                         std::getline(fh, bit, ' ');
747                         row.oldParam1 = atoi(trim(bit).c_str());
748                         std::getline(fh, bit, ' ');
749                         row.oldParam2 = atoi(trim(bit).c_str());
750                         row.oldMeta   = trim(deSerializeJsonString(fh));
751                         std::getline(fh, bit, ' ');
752                         row.newNode   = getNodeId(trim(deSerializeJsonString(fh)));
753                         std::getline(fh, bit, ' ');
754                         std::getline(fh, bit, ' ');
755                         row.newParam1 = atoi(trim(bit).c_str());
756                         std::getline(fh, bit, ' ');
757                         row.newParam2 = atoi(trim(bit).c_str());
758                         row.newMeta   = trim(deSerializeJsonString(fh));
759                         std::getline(fh, bit, ' ');
760                         std::getline(fh, bit, ' ');
761                         std::getline(fh, bit);
762                         row.guessed = (int)(trim(bit) == "actor_is_guess");
763                 } else {
764                         errorstream << "Unrecognized rollback action type \""
765                                 << bit << "\"!" << std::endl;
766                         continue;
767                 }
768
769                 registerRow(row);
770                 ++i;
771
772                 if (time(0) - t >= 1) {
773                         SQLRES(sqlite3_step(stmt_commit), SQLITE_DONE);
774                         sqlite3_reset(stmt_commit);
775                         t = time(0);
776                         std::cout
777                                 << " Done: " << static_cast<int>((static_cast<float>(fh.tellg()) / static_cast<float>(file_size)) * 100) << "%"
778                                 << " Speed: " << i / (t - start) << "/second     \r" << std::flush;
779                         SQLRES(sqlite3_step(stmt_begin), SQLITE_DONE);
780                         sqlite3_reset(stmt_begin);
781                 }
782         } while (fh.good());
783         SQLRES(sqlite3_step(stmt_commit), SQLITE_DONE);
784         sqlite3_reset(stmt_commit);
785
786         SQLOK(sqlite3_finalize(stmt_begin));
787         SQLOK(sqlite3_finalize(stmt_commit));
788
789         std::cout
790                 << " Done: 100%                                  " << std::endl
791                 << "Now you can delete the old rollback.txt file." << std::endl;
792 }
793
794
795 // Get nearness factor for subject's action for this action
796 // Return value: 0 = impossible, >0 = factor
797 float RollbackManager::getSuspectNearness(bool is_guess, v3s16 suspect_p,
798                 time_t suspect_t, v3s16 action_p, time_t action_t)
799 {
800         // Suspect cannot cause things in the past
801         if (action_t < suspect_t) {
802                 return 0;        // 0 = cannot be
803         }
804         // Start from 100
805         int f = 100;
806         // Distance (1 node = -x points)
807         f -= POINTS_PER_NODE * intToFloat(suspect_p, 1).getDistanceFrom(intToFloat(action_p, 1));
808         // Time (1 second = -x points)
809         f -= 1 * (action_t - suspect_t);
810         // If is a guess, halve the points
811         if (is_guess) {
812                 f *= 0.5;
813         }
814         // Limit to 0
815         if (f < 0) {
816                 f = 0;
817         }
818         return f;
819 }
820
821
822 void RollbackManager::reportAction(const RollbackAction &action_)
823 {
824         // Ignore if not important
825         if (!action_.isImportant(gamedef)) {
826                 return;
827         }
828
829         RollbackAction action = action_;
830         action.unix_time = time(0);
831
832         // Figure out actor
833         action.actor = current_actor;
834         action.actor_is_guess = current_actor_is_guess;
835
836         if (action.actor.empty()) { // If actor is not known, find out suspect or cancel
837                 v3s16 p;
838                 if (!action.getPosition(&p)) {
839                         return;
840                 }
841
842                 action.actor = getSuspect(p, 83, 1);
843                 if (action.actor.empty()) {
844                         return;
845                 }
846
847                 action.actor_is_guess = true;
848         }
849
850         addAction(action);
851 }
852
853 std::string RollbackManager::getActor()
854 {
855         return current_actor;
856 }
857
858 bool RollbackManager::isActorGuess()
859 {
860         return current_actor_is_guess;
861 }
862
863 void RollbackManager::setActor(const std::string & actor, bool is_guess)
864 {
865         current_actor = actor;
866         current_actor_is_guess = is_guess;
867 }
868
869 std::string RollbackManager::getSuspect(v3s16 p, float nearness_shortcut,
870                 float min_nearness)
871 {
872         if (!current_actor.empty()) {
873                 return current_actor;
874         }
875         int cur_time = time(0);
876         time_t first_time = cur_time - (100 - min_nearness);
877         RollbackAction likely_suspect;
878         float likely_suspect_nearness = 0;
879         for (std::list<RollbackAction>::const_reverse_iterator
880              i = action_latest_buffer.rbegin();
881              i != action_latest_buffer.rend(); ++i) {
882                 if (i->unix_time < first_time) {
883                         break;
884                 }
885                 if (i->actor.empty()) {
886                         continue;
887                 }
888                 // Find position of suspect or continue
889                 v3s16 suspect_p;
890                 if (!i->getPosition(&suspect_p)) {
891                         continue;
892                 }
893                 float f = getSuspectNearness(i->actor_is_guess, suspect_p,
894                                              i->unix_time, p, cur_time);
895                 if (f >= min_nearness && f > likely_suspect_nearness) {
896                         likely_suspect_nearness = f;
897                         likely_suspect = *i;
898                         if (likely_suspect_nearness >= nearness_shortcut) {
899                                 break;
900                         }
901                 }
902         }
903         // No likely suspect was found
904         if (likely_suspect_nearness == 0) {
905                 return "";
906         }
907         // Likely suspect was found
908         return likely_suspect.actor;
909 }
910
911
912 void RollbackManager::flush()
913 {
914         sqlite3_exec(db, "BEGIN", NULL, NULL, NULL);
915
916         std::list<RollbackAction>::const_iterator iter;
917
918         for (iter  = action_todisk_buffer.begin();
919                         iter != action_todisk_buffer.end();
920                         ++iter) {
921                 if (iter->actor.empty()) {
922                         continue;
923                 }
924
925                 registerRow(actionRowFromRollbackAction(*iter));
926         }
927
928         sqlite3_exec(db, "COMMIT", NULL, NULL, NULL);
929         action_todisk_buffer.clear();
930 }
931
932
933 void RollbackManager::addAction(const RollbackAction & action)
934 {
935         action_todisk_buffer.push_back(action);
936         action_latest_buffer.push_back(action);
937
938         // Flush to disk sometimes
939         if (action_todisk_buffer.size() >= 500) {
940                 flush();
941         }
942 }
943
944 std::list<RollbackAction> RollbackManager::getEntriesSince(time_t first_time)
945 {
946         flush();
947         return getActionsSince(first_time);
948 }
949
950 std::list<RollbackAction> RollbackManager::getNodeActors(v3s16 pos, int range,
951                 time_t seconds, int limit)
952 {
953         flush();
954         time_t cur_time = time(0);
955         time_t first_time = cur_time - seconds;
956
957         return getActionsSince_range(first_time, pos, range, limit);
958 }
959
960 std::list<RollbackAction> RollbackManager::getRevertActions(
961                 const std::string &actor_filter,
962                 time_t seconds)
963 {
964         time_t cur_time = time(0);
965         time_t first_time = cur_time - seconds;
966
967         flush();
968
969         return getActionsSince(first_time, actor_filter);
970 }
971