#!/usr/bin/tclsh

# Copyright IBM Corp. 2016. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# 		 http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

set usage {
Usage: checkAgreement ?... options ...? [... peers ...]

This script uses the 'fabricLogger' to check that a network of peers agree on
the contents of the blockchain. At present this type of check can only be made
in a steady-state where no more transactions are being issued, and all issued
transactions have been recorded.

Note that the agreement check will likely fail (by design) if the network is
running NOOPS consensus and transactions are being sent to multiple
peers. This is because NOOPS does not guarantee transaction
ordering. Therefore the script fails if the busywork 'network' file indicates
that the network is running NOOPS.

By default, the peer network is defined by the $BUSYWORK_HOME/network file.
However, if one or more peers are provided on the command line, those peers
will be used instead, and the -port option defines the default REST API port
to use if an explicit peer does not include an explicit port. If the explicit
peer network is running NOOPS then this script will likely fail.

If there are fewer than 2 peers this script simply exits normally, unless you
use the -dupCheck option in which case it will log the 1 peer and
duplicate-check it.

This script uses the 'fabricLogger' to create a file in $BUSYWORK_HOME named
<peerN>.chain for each of the peers, and then does a transitive 'diff' to
check that they all match. That is, <peer0>.chain is compared to
<peer1>.chain, <peer1>.chain is compared to <peer2>.chain, etc. All that is
reported by the script is whether the chains match or not.

If all chains match (and optional duplicate checks are OK), the script exits
normally after deleting all of the *.chain files. If there is a mismatch or
duplicates, the script exits abnormally and the *.chain files remain behind in
the $BUSYWORK_HOME for further analysis. The -keep/-delete option overrides
the defaults for keeping/deleting the blockchain logs.

Optional parameters. Default values are given after the :

-h | -help | --help : None

    Print this usage message and exit normally.

-dir <directory> : N/A

    If specified, put the logs in <directory> instead of $BUSYWORK_HOME.

-dupCheck | -noDupCheck : -noDupCheck

    If -dupCheck is specified, then after collecting the diff-ing the logs,
    the script will check the logs to see if there are any duplicate
    transactions. If the logs all match only the first one is checked.

-keep | -delete : See notes above

    If one of these options is specified, then the log files are either kept
    or deleted regardless of the outcome of the comparison.

-port <n> : 7050

    The default REST API port. Only used if explicit peers are used and an
    explicit peer specification does not include a port specifiaction.
}


############################################################################
# Helper Routines
############################################################################

# Return the number of duplicate transactions in a file
proc dupCheck {i_file} {

    note {} "Checking for duplicates in file $i_file"

    set rv 0

    set lines [split [read [set stream [open $i_file r]]] \n]
    close $stream

    set lineNumber 0
    set dups {}
    set blocks 0
    set deploys 0
    set invokes 0

    foreach line $lines {
        incr lineNumber
        if {[null $line]} break
        set key [lindex $line 0]
        switch $key {
            b {
                incr blocks
            }
            d -
            i {
                if {$key eq "d"} {
                    incr deploys
                } else {
                    incr invokes
                }
                set id [lindex $line 1]
                if {[info exists tx($id)]} {
                    if {![null $tx($id)]} {
                        lappend dups $id
                        lappend dupLines($id) $tx($id)
                        set tx($id) {}
                    }
                    lappend dupLines($id) $lineNumber
                } else {
                    set tx($id) $lineNumber
                }
            }
            default {
                errorExit \
                    "Blockchain log file entry not recognized (below)\n" \
                    $line "\n"
            }
        }
    }

    note {} "  $blocks Blocks; $deploys Deploys; $invokes Invokes"

    if {![null $dups]} {

        err {} "  Duplicate Report : [llength $dups] Duplicated Transactions"
        err {} "    <TX ID>                              <Line Numbers>"
        foreach dup $dups {
            err {} "    $dup $dupLines($dup)"
        }
    }

    return [llength $dups]
}

############################################################################
# Option Processing
############################################################################

lappend auto_path [file dirname [info script]]/../tcl

package require busywork

signal trap SIGINT {exit 0};    # Exit normally after ^C from terminal

setLoggingPrefix checkAgreement

set options {
    {enum {-h -help --help}       parms(help)     0 p_help}
    {key  -dir                    parms(dir)      {} p_dir}
    {bool {-dupCheck -noDupCheck} parms(dupCheck) 0}
    {bool {-keep -delete}         parms(keep)     0 p_keep}
    {key  -port                   parms(port)     7050}

}

mapKeywordArgs $argv $options parms(explicitPeers)

if {$p_help} {
    puts $usage
    exit 0
}

setLoggingLevel {} note

if {!$p_dir} {
    parms dir [busywork::home]
}

if {[null [parms explicitPeers]]} {
    if {[catch {busywork::networkToArray ::parms network.} msg]} {
        errorExit $msg
    }
    if {[parms network.consensus] eq "noops"} {
        puts stderr $usage
        err err "checkAgreement does not support NOOPS consensus"
        errorExit "Search for 'NOOPS' in the usage statement to understand why"
    }
    parms peers [parms network.peer.restAddresses]
} else {
    parms peers [addPortToHosts [parms explicitPeers] [parms port]]
}

if {([llength [parms peers]] < 2) &&
    ([parms dupCheck] && ([llength [parms peers]] == 0))} {
    note {} \
        "Nothing to do for [llength [parms peers]] peers; " \
        "Exiting normally"
    exit 0
}

parms files [mapeach peer [parms peers] {return [parms dir]/$peer.chain}]


############################################################################
# The script
############################################################################

# We 'fork' for concurrency rather than using background jobs to improve error
# reporting.

set logger [busywork::bin]/fabricLogger

set errors 0
set pids {}
set goodPeers {}
set goodFiles {}

note {} "Blockchain logs will be written into [parms dir]"
foreach peer [parms peers] file [parms files] {
    note {} "Logging $peer into $file"
    flush stdout
    flush stderr
    set pid [fork]
    switch $pid {
        -1 {
            errorExit "Fork failed"
        }
        0 {
            if {[catch {exec $logger -file $file $peer} reason]} {
                err {} "Logging peer $peer failed : $reason"
                err {} "This peer will be ignored"
                exit 1
            }
            exit 0
        }
        default {
            lappend pids $pid
        }
    }
}

waitPIDs $pids digest
foreach pid $pids peer [parms peers] file [parms files] {
    if {$digest($pid.ok)} {
        lappend goodPeers $peer
        lappend goodFiles $file
    } else {
        incr errors
    }
}

if {[llength $goodPeers] > 1} {
    note {} "Checking agreement"
}

for {set i 0; set j 1} {$j < [llength $goodPeers]} {incr i; incr j} {

    if {[catch {exec diff -q \
                    [lindex $goodFiles $i] \
                    [lindex $goodFiles $j]}]} {
        err {} \
            "Peers [lindex $goodPeers $i] and [lindex $goodPeers $j] " \
            "disagree."
        incr errors
    } else {
        note {} "Peers [lindex $goodPeers $i] and [lindex $goodPeers $j] agree"
    }
}

if {[parms dupCheck] && ![null $goodFiles]} {
    if {$errors} {
        foreach file $goodFiles {
            incr errors [dupCheck $file]
        }
    } else {
        incr errors [dupCheck [lindex $goodFiles 0]]
    }
}

if {$p_keep} {
    if {[parms keep]} {
        set fileDisposition kept
    } else {
        set fileDisposition deleted
    }
} else {
    if {$errors} {
        set fileDisposition kept
    } else {
        set fileDisposition deleted
    }
}

if {$fileDisposition eq "deleted"} {
    foreach file [parms files] {
        exec rm -f $file
    }
}

if {$errors} {
        errorExit \
            "Aborting due to errors, disgreement or duplicates; " \
            "All log files have been $fileDisposition"
}

note {} "All peers agree; All log files have been $fileDisposition"
