]> git.lizzy.rs Git - minetest.git/blob - src/rollback.cpp
Remove old rollback migration code (#13082)
[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         database_path = world_path + DIR_DELIM "rollback.sqlite";
100
101         initDatabase();
102 }
103
104
105 RollbackManager::~RollbackManager()
106 {
107         flush();
108
109         FINALIZE_STATEMENT(stmt_insert);
110         FINALIZE_STATEMENT(stmt_replace);
111         FINALIZE_STATEMENT(stmt_select);
112         FINALIZE_STATEMENT(stmt_select_range);
113         FINALIZE_STATEMENT(stmt_select_withActor);
114         FINALIZE_STATEMENT(stmt_knownActor_select);
115         FINALIZE_STATEMENT(stmt_knownActor_insert);
116         FINALIZE_STATEMENT(stmt_knownNode_select);
117         FINALIZE_STATEMENT(stmt_knownNode_insert);
118
119         SQLOK_ERRSTREAM(sqlite3_close(db), "Could not close db");
120 }
121
122
123 void RollbackManager::registerNewActor(const int id, const std::string &name)
124 {
125         Entity actor = {id, name};
126         knownActors.push_back(actor);
127 }
128
129
130 void RollbackManager::registerNewNode(const int id, const std::string &name)
131 {
132         Entity node = {id, name};
133         knownNodes.push_back(node);
134 }
135
136
137 int RollbackManager::getActorId(const std::string &name)
138 {
139         for (std::vector<Entity>::const_iterator iter = knownActors.begin();
140                         iter != knownActors.end(); ++iter) {
141                 if (iter->name == name) {
142                         return iter->id;
143                 }
144         }
145
146         SQLOK(sqlite3_bind_text(stmt_knownActor_insert, 1, name.c_str(), name.size(), NULL));
147         SQLRES(sqlite3_step(stmt_knownActor_insert), SQLITE_DONE);
148         SQLOK(sqlite3_reset(stmt_knownActor_insert));
149
150         int id = sqlite3_last_insert_rowid(db);
151         registerNewActor(id, name);
152
153         return id;
154 }
155
156
157 int RollbackManager::getNodeId(const std::string &name)
158 {
159         for (std::vector<Entity>::const_iterator iter = knownNodes.begin();
160                         iter != knownNodes.end(); ++iter) {
161                 if (iter->name == name) {
162                         return iter->id;
163                 }
164         }
165
166         SQLOK(sqlite3_bind_text(stmt_knownNode_insert, 1, name.c_str(), name.size(), NULL));
167         SQLRES(sqlite3_step(stmt_knownNode_insert), SQLITE_DONE);
168         SQLOK(sqlite3_reset(stmt_knownNode_insert));
169
170         int id = sqlite3_last_insert_rowid(db);
171         registerNewNode(id, name);
172
173         return id;
174 }
175
176
177 const char * RollbackManager::getActorName(const int id)
178 {
179         for (std::vector<Entity>::const_iterator iter = knownActors.begin();
180                         iter != knownActors.end(); ++iter) {
181                 if (iter->id == id) {
182                         return iter->name.c_str();
183                 }
184         }
185
186         return "";
187 }
188
189
190 const char * RollbackManager::getNodeName(const int id)
191 {
192         for (std::vector<Entity>::const_iterator iter = knownNodes.begin();
193                         iter != knownNodes.end(); ++iter) {
194                 if (iter->id == id) {
195                         return iter->name.c_str();
196                 }
197         }
198
199         return "";
200 }
201
202
203 bool RollbackManager::createTables()
204 {
205         SQLOK(sqlite3_exec(db,
206                 "CREATE TABLE IF NOT EXISTS `actor` (\n"
207                 "       `id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,\n"
208                 "       `name` TEXT NOT NULL\n"
209                 ");\n"
210                 "CREATE TABLE IF NOT EXISTS `node` (\n"
211                 "       `id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,\n"
212                 "       `name` TEXT NOT NULL\n"
213                 ");\n"
214                 "CREATE TABLE IF NOT EXISTS `action` (\n"
215                 "       `id` INTEGER PRIMARY KEY AUTOINCREMENT,\n"
216                 "       `actor` INTEGER NOT NULL,\n"
217                 "       `timestamp` TIMESTAMP NOT NULL,\n"
218                 "       `type` INTEGER NOT NULL,\n"
219                 "       `list` TEXT,\n"
220                 "       `index` INTEGER,\n"
221                 "       `add` INTEGER,\n"
222                 "       `stackNode` INTEGER,\n"
223                 "       `stackQuantity` INTEGER,\n"
224                 "       `nodeMeta` INTEGER,\n"
225                 "       `x` INT,\n"
226                 "       `y` INT,\n"
227                 "       `z` INT,\n"
228                 "       `oldNode` INTEGER,\n"
229                 "       `oldParam1` INTEGER,\n"
230                 "       `oldParam2` INTEGER,\n"
231                 "       `oldMeta` TEXT,\n"
232                 "       `newNode` INTEGER,\n"
233                 "       `newParam1` INTEGER,\n"
234                 "       `newParam2` INTEGER,\n"
235                 "       `newMeta` TEXT,\n"
236                 "       `guessedActor` INTEGER,\n"
237                 "       FOREIGN KEY (`actor`) REFERENCES `actor`(`id`),\n"
238                 "       FOREIGN KEY (`stackNode`) REFERENCES `node`(`id`),\n"
239                 "       FOREIGN KEY (`oldNode`)   REFERENCES `node`(`id`),\n"
240                 "       FOREIGN KEY (`newNode`)   REFERENCES `node`(`id`)\n"
241                 ");\n"
242                 "CREATE INDEX IF NOT EXISTS `actionIndex` ON `action`(`x`,`y`,`z`,`timestamp`,`actor`);\n",
243                 NULL, NULL, NULL));
244         verbosestream << "SQL Rollback: SQLite3 database structure was created" << std::endl;
245
246         return true;
247 }
248
249
250 bool RollbackManager::initDatabase()
251 {
252         verbosestream << "RollbackManager: Database connection setup" << std::endl;
253
254         bool needs_create = !fs::PathExists(database_path);
255         SQLOK(sqlite3_open_v2(database_path.c_str(), &db,
256                         SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, NULL));
257
258         if (needs_create) {
259                 createTables();
260         }
261
262         SQLOK(sqlite3_prepare_v2(db,
263                 "INSERT INTO `action` (\n"
264                 "       `actor`, `timestamp`, `type`,\n"
265                 "       `list`, `index`, `add`, `stackNode`, `stackQuantity`, `nodeMeta`,\n"
266                 "       `x`, `y`, `z`,\n"
267                 "       `oldNode`, `oldParam1`, `oldParam2`, `oldMeta`,\n"
268                 "       `newNode`, `newParam1`, `newParam2`, `newMeta`,\n"
269                 "       `guessedActor`\n"
270                 ") VALUES (\n"
271                 "       ?, ?, ?,\n"
272                 "       ?, ?, ?, ?, ?, ?,\n"
273                 "       ?, ?, ?,\n"
274                 "       ?, ?, ?, ?,\n"
275                 "       ?, ?, ?, ?,\n"
276                 "       ?"
277                 ");",
278                 -1, &stmt_insert, NULL));
279
280         SQLOK(sqlite3_prepare_v2(db,
281                 "REPLACE INTO `action` (\n"
282                 "       `actor`, `timestamp`, `type`,\n"
283                 "       `list`, `index`, `add`, `stackNode`, `stackQuantity`, `nodeMeta`,\n"
284                 "       `x`, `y`, `z`,\n"
285                 "       `oldNode`, `oldParam1`, `oldParam2`, `oldMeta`,\n"
286                 "       `newNode`, `newParam1`, `newParam2`, `newMeta`,\n"
287                 "       `guessedActor`, `id`\n"
288                 ") VALUES (\n"
289                 "       ?, ?, ?,\n"
290                 "       ?, ?, ?, ?, ?, ?,\n"
291                 "       ?, ?, ?,\n"
292                 "       ?, ?, ?, ?,\n"
293                 "       ?, ?, ?, ?,\n"
294                 "       ?, ?\n"
295                 ");",
296                 -1, &stmt_replace, NULL));
297
298         SQLOK(sqlite3_prepare_v2(db,
299                 "SELECT\n"
300                 "       `actor`, `timestamp`, `type`,\n"
301                 "       `list`, `index`, `add`, `stackNode`, `stackQuantity`, `nodemeta`,\n"
302                 "       `x`, `y`, `z`,\n"
303                 "       `oldNode`, `oldParam1`, `oldParam2`, `oldMeta`,\n"
304                 "       `newNode`, `newParam1`, `newParam2`, `newMeta`,\n"
305                 "       `guessedActor`\n"
306                 " FROM `action`\n"
307                 " WHERE `timestamp` >= ?\n"
308                 " ORDER BY `timestamp` DESC, `id` DESC",
309                 -1, &stmt_select, NULL));
310
311         SQLOK(sqlite3_prepare_v2(db,
312                 "SELECT\n"
313                 "       `actor`, `timestamp`, `type`,\n"
314                 "       `list`, `index`, `add`, `stackNode`, `stackQuantity`, `nodemeta`,\n"
315                 "       `x`, `y`, `z`,\n"
316                 "       `oldNode`, `oldParam1`, `oldParam2`, `oldMeta`,\n"
317                 "       `newNode`, `newParam1`, `newParam2`, `newMeta`,\n"
318                 "       `guessedActor`\n"
319                 "FROM `action`\n"
320                 "WHERE `timestamp` >= ?\n"
321                 "       AND `x` IS NOT NULL\n"
322                 "       AND `y` IS NOT NULL\n"
323                 "       AND `z` IS NOT NULL\n"
324                 "       AND `x` BETWEEN ? AND ?\n"
325                 "       AND `y` BETWEEN ? AND ?\n"
326                 "       AND `z` BETWEEN ? AND ?\n"
327                 "ORDER BY `timestamp` DESC, `id` DESC\n"
328                 "LIMIT 0,?",
329                 -1, &stmt_select_range, NULL));
330
331         SQLOK(sqlite3_prepare_v2(db,
332                 "SELECT\n"
333                 "       `actor`, `timestamp`, `type`,\n"
334                 "       `list`, `index`, `add`, `stackNode`, `stackQuantity`, `nodemeta`,\n"
335                 "       `x`, `y`, `z`,\n"
336                 "       `oldNode`, `oldParam1`, `oldParam2`, `oldMeta`,\n"
337                 "       `newNode`, `newParam1`, `newParam2`, `newMeta`,\n"
338                 "       `guessedActor`\n"
339                 "FROM `action`\n"
340                 "WHERE `timestamp` >= ?\n"
341                 "       AND `actor` = ?\n"
342                 "ORDER BY `timestamp` DESC, `id` DESC\n",
343                 -1, &stmt_select_withActor, NULL));
344
345         SQLOK(sqlite3_prepare_v2(db, "SELECT `id`, `name` FROM `actor`",
346                         -1, &stmt_knownActor_select, NULL));
347
348         SQLOK(sqlite3_prepare_v2(db, "INSERT INTO `actor` (`name`) VALUES (?)",
349                         -1, &stmt_knownActor_insert, NULL));
350
351         SQLOK(sqlite3_prepare_v2(db, "SELECT `id`, `name` FROM `node`",
352                         -1, &stmt_knownNode_select, NULL));
353
354         SQLOK(sqlite3_prepare_v2(db, "INSERT INTO `node` (`name`) VALUES (?)",
355                         -1, &stmt_knownNode_insert, NULL));
356
357         verbosestream << "SQL prepared statements setup correctly" << std::endl;
358
359         while (sqlite3_step(stmt_knownActor_select) == SQLITE_ROW) {
360                 registerNewActor(
361                         sqlite3_column_int(stmt_knownActor_select, 0),
362                         reinterpret_cast<const char *>(sqlite3_column_text(stmt_knownActor_select, 1))
363                 );
364         }
365         SQLOK(sqlite3_reset(stmt_knownActor_select));
366
367         while (sqlite3_step(stmt_knownNode_select) == SQLITE_ROW) {
368                 registerNewNode(
369                         sqlite3_column_int(stmt_knownNode_select, 0),
370                         reinterpret_cast<const char *>(sqlite3_column_text(stmt_knownNode_select, 1))
371                 );
372         }
373         SQLOK(sqlite3_reset(stmt_knownNode_select));
374
375         return needs_create;
376 }
377
378
379 bool RollbackManager::registerRow(const ActionRow & row)
380 {
381         sqlite3_stmt * stmt_do = (row.id) ? stmt_replace : stmt_insert;
382
383         bool nodeMeta = false;
384
385         SQLOK(sqlite3_bind_int  (stmt_do, 1, row.actor));
386         SQLOK(sqlite3_bind_int64(stmt_do, 2, row.timestamp));
387         SQLOK(sqlite3_bind_int  (stmt_do, 3, row.type));
388
389         if (row.type == RollbackAction::TYPE_MODIFY_INVENTORY_STACK) {
390                 const std::string & loc = row.location;
391                 nodeMeta = (loc.substr(0, 9) == "nodemeta:");
392
393                 SQLOK(sqlite3_bind_text(stmt_do, 4, row.list.c_str(), row.list.size(), NULL));
394                 SQLOK(sqlite3_bind_int (stmt_do, 5, row.index));
395                 SQLOK(sqlite3_bind_int (stmt_do, 6, row.add));
396                 SQLOK(sqlite3_bind_int (stmt_do, 7, row.stack.id));
397                 SQLOK(sqlite3_bind_int (stmt_do, 8, row.stack.count));
398                 SQLOK(sqlite3_bind_int (stmt_do, 9, (int) nodeMeta));
399
400                 if (nodeMeta) {
401                         std::string::size_type p1, p2;
402                         p1 = loc.find(':') + 1;
403                         p2 = loc.find(',');
404                         std::string x = loc.substr(p1, p2 - p1);
405                         p1 = p2 + 1;
406                         p2 = loc.find(',', p1);
407                         std::string y = loc.substr(p1, p2 - p1);
408                         std::string z = loc.substr(p2 + 1);
409                         SQLOK(sqlite3_bind_int(stmt_do, 10, atoi(x.c_str())));
410                         SQLOK(sqlite3_bind_int(stmt_do, 11, atoi(y.c_str())));
411                         SQLOK(sqlite3_bind_int(stmt_do, 12, atoi(z.c_str())));
412                 }
413         } else {
414                 SQLOK(sqlite3_bind_null(stmt_do, 4));
415                 SQLOK(sqlite3_bind_null(stmt_do, 5));
416                 SQLOK(sqlite3_bind_null(stmt_do, 6));
417                 SQLOK(sqlite3_bind_null(stmt_do, 7));
418                 SQLOK(sqlite3_bind_null(stmt_do, 8));
419                 SQLOK(sqlite3_bind_null(stmt_do, 9));
420         }
421
422         if (row.type == RollbackAction::TYPE_SET_NODE) {
423                 SQLOK(sqlite3_bind_int (stmt_do, 10, row.x));
424                 SQLOK(sqlite3_bind_int (stmt_do, 11, row.y));
425                 SQLOK(sqlite3_bind_int (stmt_do, 12, row.z));
426                 SQLOK(sqlite3_bind_int (stmt_do, 13, row.oldNode));
427                 SQLOK(sqlite3_bind_int (stmt_do, 14, row.oldParam1));
428                 SQLOK(sqlite3_bind_int (stmt_do, 15, row.oldParam2));
429                 SQLOK(sqlite3_bind_text(stmt_do, 16, row.oldMeta.c_str(), row.oldMeta.size(), NULL));
430                 SQLOK(sqlite3_bind_int (stmt_do, 17, row.newNode));
431                 SQLOK(sqlite3_bind_int (stmt_do, 18, row.newParam1));
432                 SQLOK(sqlite3_bind_int (stmt_do, 19, row.newParam2));
433                 SQLOK(sqlite3_bind_text(stmt_do, 20, row.newMeta.c_str(), row.newMeta.size(), NULL));
434                 SQLOK(sqlite3_bind_int (stmt_do, 21, row.guessed ? 1 : 0));
435         } else {
436                 if (!nodeMeta) {
437                         SQLOK(sqlite3_bind_null(stmt_do, 10));
438                         SQLOK(sqlite3_bind_null(stmt_do, 11));
439                         SQLOK(sqlite3_bind_null(stmt_do, 12));
440                 }
441                 SQLOK(sqlite3_bind_null(stmt_do, 13));
442                 SQLOK(sqlite3_bind_null(stmt_do, 14));
443                 SQLOK(sqlite3_bind_null(stmt_do, 15));
444                 SQLOK(sqlite3_bind_null(stmt_do, 16));
445                 SQLOK(sqlite3_bind_null(stmt_do, 17));
446                 SQLOK(sqlite3_bind_null(stmt_do, 18));
447                 SQLOK(sqlite3_bind_null(stmt_do, 19));
448                 SQLOK(sqlite3_bind_null(stmt_do, 20));
449                 SQLOK(sqlite3_bind_null(stmt_do, 21));
450         }
451
452         if (row.id) {
453                 SQLOK(sqlite3_bind_int(stmt_do, 22, row.id));
454         }
455
456         int written = sqlite3_step(stmt_do);
457
458         SQLOK(sqlite3_reset(stmt_do));
459
460         return written == SQLITE_DONE;
461 }
462
463
464 const std::list<ActionRow> RollbackManager::actionRowsFromSelect(sqlite3_stmt* stmt)
465 {
466         std::list<ActionRow> rows;
467         const unsigned char * text;
468         size_t size;
469
470         while (sqlite3_step(stmt) == SQLITE_ROW) {
471                 ActionRow row;
472
473                 row.actor     = sqlite3_column_int  (stmt, 0);
474                 row.timestamp = sqlite3_column_int64(stmt, 1);
475                 row.type      = sqlite3_column_int  (stmt, 2);
476                 row.nodeMeta  = 0;
477
478                 if (row.type == RollbackAction::TYPE_MODIFY_INVENTORY_STACK) {
479                         text = sqlite3_column_text (stmt, 3);
480                         size = sqlite3_column_bytes(stmt, 3);
481                         row.list        = std::string(reinterpret_cast<const char*>(text), size);
482                         row.index       = sqlite3_column_int(stmt, 4);
483                         row.add         = sqlite3_column_int(stmt, 5);
484                         row.stack.id    = sqlite3_column_int(stmt, 6);
485                         row.stack.count = sqlite3_column_int(stmt, 7);
486                         row.nodeMeta    = sqlite3_column_int(stmt, 8);
487                 }
488
489                 if (row.type == RollbackAction::TYPE_SET_NODE || row.nodeMeta) {
490                         row.x = sqlite3_column_int(stmt,  9);
491                         row.y = sqlite3_column_int(stmt, 10);
492                         row.z = sqlite3_column_int(stmt, 11);
493                 }
494
495                 if (row.type == RollbackAction::TYPE_SET_NODE) {
496                         row.oldNode   = sqlite3_column_int(stmt, 12);
497                         row.oldParam1 = sqlite3_column_int(stmt, 13);
498                         row.oldParam2 = sqlite3_column_int(stmt, 14);
499                         text = sqlite3_column_text (stmt, 15);
500                         size = sqlite3_column_bytes(stmt, 15);
501                         row.oldMeta   = std::string(reinterpret_cast<const char*>(text), size);
502                         row.newNode   = sqlite3_column_int(stmt, 16);
503                         row.newParam1 = sqlite3_column_int(stmt, 17);
504                         row.newParam2 = sqlite3_column_int(stmt, 18);
505                         text = sqlite3_column_text(stmt, 19);
506                         size = sqlite3_column_bytes(stmt, 19);
507                         row.newMeta   = std::string(reinterpret_cast<const char*>(text), size);
508                         row.guessed   = sqlite3_column_int(stmt, 20);
509                 }
510
511                 if (row.nodeMeta) {
512                         row.location = "nodemeta:";
513                         row.location += itos(row.x);
514                         row.location += ',';
515                         row.location += itos(row.y);
516                         row.location += ',';
517                         row.location += itos(row.z);
518                 } else {
519                         row.location = getActorName(row.actor);
520                 }
521
522                 rows.push_back(row);
523         }
524
525         SQLOK(sqlite3_reset(stmt));
526
527         return rows;
528 }
529
530
531 ActionRow RollbackManager::actionRowFromRollbackAction(const RollbackAction & action)
532 {
533         ActionRow row;
534
535         row.id        = 0;
536         row.actor     = getActorId(action.actor);
537         row.timestamp = action.unix_time;
538         row.type      = action.type;
539
540         if (row.type == RollbackAction::TYPE_MODIFY_INVENTORY_STACK) {
541                 row.location = action.inventory_location;
542                 row.list     = action.inventory_list;
543                 row.index    = action.inventory_index;
544                 row.add      = action.inventory_add;
545                 row.stack    = action.inventory_stack;
546                 row.stack.id = getNodeId(row.stack.name);
547         } else {
548                 row.x         = action.p.X;
549                 row.y         = action.p.Y;
550                 row.z         = action.p.Z;
551                 row.oldNode   = getNodeId(action.n_old.name);
552                 row.oldParam1 = action.n_old.param1;
553                 row.oldParam2 = action.n_old.param2;
554                 row.oldMeta   = action.n_old.meta;
555                 row.newNode   = getNodeId(action.n_new.name);
556                 row.newParam1 = action.n_new.param1;
557                 row.newParam2 = action.n_new.param2;
558                 row.newMeta   = action.n_new.meta;
559                 row.guessed   = action.actor_is_guess;
560         }
561
562         return row;
563 }
564
565
566 const std::list<RollbackAction> RollbackManager::rollbackActionsFromActionRows(
567                 const std::list<ActionRow> & rows)
568 {
569         std::list<RollbackAction> actions;
570
571         for (const ActionRow &row : rows) {
572                 RollbackAction action;
573                 action.actor     = (row.actor) ? getActorName(row.actor) : "";
574                 action.unix_time = row.timestamp;
575                 action.type      = static_cast<RollbackAction::Type>(row.type);
576
577                 switch (action.type) {
578                 case RollbackAction::TYPE_MODIFY_INVENTORY_STACK:
579                         action.inventory_location = row.location;
580                         action.inventory_list     = row.list;
581                         action.inventory_index    = row.index;
582                         action.inventory_add      = row.add;
583                         action.inventory_stack    = row.stack;
584                         if (action.inventory_stack.name.empty()) {
585                                 action.inventory_stack.name = getNodeName(row.stack.id);
586                         }
587                         break;
588
589                 case RollbackAction::TYPE_SET_NODE:
590                         action.p            = v3s16(row.x, row.y, row.z);
591                         action.n_old.name   = getNodeName(row.oldNode);
592                         action.n_old.param1 = row.oldParam1;
593                         action.n_old.param2 = row.oldParam2;
594                         action.n_old.meta   = row.oldMeta;
595                         action.n_new.name   = getNodeName(row.newNode);
596                         action.n_new.param1 = row.newParam1;
597                         action.n_new.param2 = row.newParam2;
598                         action.n_new.meta   = row.newMeta;
599                         break;
600
601                 default:
602                         throw ("W.T.F.");
603                         break;
604                 }
605
606                 actions.push_back(action);
607         }
608
609         return actions;
610 }
611
612
613 const std::list<ActionRow> RollbackManager::getRowsSince(time_t firstTime, const std::string & actor)
614 {
615         sqlite3_stmt *stmt_stmt = actor.empty() ? stmt_select : stmt_select_withActor;
616         sqlite3_bind_int64(stmt_stmt, 1, firstTime);
617
618         if (!actor.empty()) {
619                 sqlite3_bind_int(stmt_stmt, 2, getActorId(actor));
620         }
621
622         const std::list<ActionRow> & rows = actionRowsFromSelect(stmt_stmt);
623         sqlite3_reset(stmt_stmt);
624
625         return rows;
626 }
627
628
629 const std::list<ActionRow> RollbackManager::getRowsSince_range(
630                 time_t start_time, v3s16 p, int range, int limit)
631 {
632
633         sqlite3_bind_int64(stmt_select_range, 1, start_time);
634         sqlite3_bind_int  (stmt_select_range, 2, static_cast<int>(p.X - range));
635         sqlite3_bind_int  (stmt_select_range, 3, static_cast<int>(p.X + range));
636         sqlite3_bind_int  (stmt_select_range, 4, static_cast<int>(p.Y - range));
637         sqlite3_bind_int  (stmt_select_range, 5, static_cast<int>(p.Y + range));
638         sqlite3_bind_int  (stmt_select_range, 6, static_cast<int>(p.Z - range));
639         sqlite3_bind_int  (stmt_select_range, 7, static_cast<int>(p.Z + range));
640         sqlite3_bind_int  (stmt_select_range, 8, limit);
641
642         const std::list<ActionRow> & rows = actionRowsFromSelect(stmt_select_range);
643         sqlite3_reset(stmt_select_range);
644
645         return rows;
646 }
647
648
649 const std::list<RollbackAction> RollbackManager::getActionsSince_range(
650                 time_t start_time, v3s16 p, int range, int limit)
651 {
652         return rollbackActionsFromActionRows(getRowsSince_range(start_time, p, range, limit));
653 }
654
655
656 const std::list<RollbackAction> RollbackManager::getActionsSince(
657                 time_t start_time, const std::string & actor)
658 {
659         return rollbackActionsFromActionRows(getRowsSince(start_time, actor));
660 }
661
662
663 // Get nearness factor for subject's action for this action
664 // Return value: 0 = impossible, >0 = factor
665 float RollbackManager::getSuspectNearness(bool is_guess, v3s16 suspect_p,
666                 time_t suspect_t, v3s16 action_p, time_t action_t)
667 {
668         // Suspect cannot cause things in the past
669         if (action_t < suspect_t) {
670                 return 0;        // 0 = cannot be
671         }
672         // Start from 100
673         int f = 100;
674         // Distance (1 node = -x points)
675         f -= POINTS_PER_NODE * intToFloat(suspect_p, 1).getDistanceFrom(intToFloat(action_p, 1));
676         // Time (1 second = -x points)
677         f -= 1 * (action_t - suspect_t);
678         // If is a guess, halve the points
679         if (is_guess) {
680                 f *= 0.5;
681         }
682         // Limit to 0
683         if (f < 0) {
684                 f = 0;
685         }
686         return f;
687 }
688
689
690 void RollbackManager::reportAction(const RollbackAction &action_)
691 {
692         // Ignore if not important
693         if (!action_.isImportant(gamedef)) {
694                 return;
695         }
696
697         RollbackAction action = action_;
698         action.unix_time = time(0);
699
700         // Figure out actor
701         action.actor = current_actor;
702         action.actor_is_guess = current_actor_is_guess;
703
704         if (action.actor.empty()) { // If actor is not known, find out suspect or cancel
705                 v3s16 p;
706                 if (!action.getPosition(&p)) {
707                         return;
708                 }
709
710                 action.actor = getSuspect(p, 83, 1);
711                 if (action.actor.empty()) {
712                         return;
713                 }
714
715                 action.actor_is_guess = true;
716         }
717
718         addAction(action);
719 }
720
721 std::string RollbackManager::getActor()
722 {
723         return current_actor;
724 }
725
726 bool RollbackManager::isActorGuess()
727 {
728         return current_actor_is_guess;
729 }
730
731 void RollbackManager::setActor(const std::string & actor, bool is_guess)
732 {
733         current_actor = actor;
734         current_actor_is_guess = is_guess;
735 }
736
737 std::string RollbackManager::getSuspect(v3s16 p, float nearness_shortcut,
738                 float min_nearness)
739 {
740         if (!current_actor.empty()) {
741                 return current_actor;
742         }
743         int cur_time = time(0);
744         time_t first_time = cur_time - (100 - min_nearness);
745         RollbackAction likely_suspect;
746         float likely_suspect_nearness = 0;
747         for (std::list<RollbackAction>::const_reverse_iterator
748              i = action_latest_buffer.rbegin();
749              i != action_latest_buffer.rend(); ++i) {
750                 if (i->unix_time < first_time) {
751                         break;
752                 }
753                 if (i->actor.empty()) {
754                         continue;
755                 }
756                 // Find position of suspect or continue
757                 v3s16 suspect_p;
758                 if (!i->getPosition(&suspect_p)) {
759                         continue;
760                 }
761                 float f = getSuspectNearness(i->actor_is_guess, suspect_p,
762                                              i->unix_time, p, cur_time);
763                 if (f >= min_nearness && f > likely_suspect_nearness) {
764                         likely_suspect_nearness = f;
765                         likely_suspect = *i;
766                         if (likely_suspect_nearness >= nearness_shortcut) {
767                                 break;
768                         }
769                 }
770         }
771         // No likely suspect was found
772         if (likely_suspect_nearness == 0) {
773                 return "";
774         }
775         // Likely suspect was found
776         return likely_suspect.actor;
777 }
778
779
780 void RollbackManager::flush()
781 {
782         sqlite3_exec(db, "BEGIN", NULL, NULL, NULL);
783
784         std::list<RollbackAction>::const_iterator iter;
785
786         for (iter  = action_todisk_buffer.begin();
787                         iter != action_todisk_buffer.end();
788                         ++iter) {
789                 if (iter->actor.empty()) {
790                         continue;
791                 }
792
793                 registerRow(actionRowFromRollbackAction(*iter));
794         }
795
796         sqlite3_exec(db, "COMMIT", NULL, NULL, NULL);
797         action_todisk_buffer.clear();
798 }
799
800
801 void RollbackManager::addAction(const RollbackAction & action)
802 {
803         action_todisk_buffer.push_back(action);
804         action_latest_buffer.push_back(action);
805
806         // Flush to disk sometimes
807         if (action_todisk_buffer.size() >= 500) {
808                 flush();
809         }
810 }
811
812 std::list<RollbackAction> RollbackManager::getNodeActors(v3s16 pos, int range,
813                 time_t seconds, int limit)
814 {
815         flush();
816         time_t cur_time = time(0);
817         time_t first_time = cur_time - seconds;
818
819         return getActionsSince_range(first_time, pos, range, limit);
820 }
821
822 std::list<RollbackAction> RollbackManager::getRevertActions(
823                 const std::string &actor_filter,
824                 time_t seconds)
825 {
826         time_t cur_time = time(0);
827         time_t first_time = cur_time - seconds;
828
829         flush();
830
831         return getActionsSince(first_time, actor_filter);
832 }
833