#!/usr/bin/env python

import util, json
from collections import defaultdict


def analyze(results):
    out = {}
    dd = {}
    for k, v in results.items():
        height = v.get('block_height')
        merkle = v.get('merkle_root')
        utxo = v.get('utxo_root')
        d = dd.get(merkle, defaultdict(int))
        d[utxo] += 1
        dd[merkle] = d
    refs = {}
    for merkle, d in dd.items():
        v = d.values()
        m = max(v)
        ref = d.keys()[v.index(m)]
        refs[merkle] = ref, m
    for k, v in results.items():
        height = v.get('block_height')
        merkle = v.get('merkle_root')
        utxo = v.get('utxo_root')
        ref_utxo, num = refs.get(merkle)
        if ref_utxo != utxo and num > 1:
            out[k] = height, merkle, utxo
    return out


peers = util.get_peers()
results = util.send_request(peers, {'method':'blockchain.headers.subscribe','params':[]})

errors = analyze(results).keys()

for n,v in sorted(results.items(), key=lambda x:x[1].get('block_height')):
    print "%40s"%n, v.get('block_height'), v.get('utxo_root'), "error" if n in errors else "ok"



