From 90b697b3bbf26637bbfc215dd336ab053cac37d2 Mon Sep 17 00:00:00 2001
From: Robert Martin-Legene <robert@nic.ar>
Date: Tue, 31 Jul 2018 11:10:03 -0300
Subject: [PATCH] Rewind rolls your local idea of the chain back a few blocks
 and tries to resynchronize. This can be good if you think you are stuck.

---
 bin/rewind.sh |  6 ++++++
 src/js.rewind | 32 ++++++++++++++++++++++++++++++++
 2 files changed, 38 insertions(+)
 create mode 100755 bin/rewind.sh
 create mode 100755 src/js.rewind

diff --git a/bin/rewind.sh b/bin/rewind.sh
new file mode 100755
index 0000000..ff4c62b
--- /dev/null
+++ b/bin/rewind.sh
@@ -0,0 +1,6 @@
+#!/bin/bash
+
+if [ -z "${BFAHOME}" ]; then echo "\$BFAHOME not set. Did you source bfa/bin/env ?" >&2; exit 1; fi
+source ${BFAHOME}/bin/libbfa.sh || exit 1
+
+geth_exec_js ${BFAHOME}/src/js.rewind
diff --git a/src/js.rewind b/src/js.rewind
new file mode 100755
index 0000000..6c40497
--- /dev/null
+++ b/src/js.rewind
@@ -0,0 +1,32 @@
+// vim:syntax:filetype=javascript:ai:sm
+// vim:expandtab:backspace=indent,eol,start:softtabstop=4
+
+// How many blocks to step back.
+var     backstep    =   6
+// If we are syncing, there's no need to rewind (I think?)
+if (!eth.syncing && eth.blockNumber > 10)
+{
+    var     max     =   0
+    // Get the maximum difficulty of all valid connected peers
+    for (x in admin.peers)
+    {
+        var xd      =   admin.peers[x].protocols.eth.difficulty
+        if (admin.peers[x].protocols.eth!="handshake" && xd>max)
+            max=xd
+    }
+    if (eth.blockNumber.totalDifficulty+200<max) {
+        console.log(
+            "Max total difficulty is "
+            + max
+            + ", but mine is just "
+            + eth.blockNumber.totalDifficulty
+            + " (in block "
+            + eth.blockNumber
+            + "). Rolling "
+            + backstep+" blocks back, to block "
+            + web3.toHex(eth.blockNumber-backstep)
+        )
+        // Rollback a bit and see if we weren't stuck just because we were stuck in a side fork.
+        debug.setHead(web3.toHex(eth.blockNumber-backstep))
+    }
+}
-- 
GitLab