#!/usr/bin/python3

import sys
import json
import requests
import time

rpchost="127.0.0.1"
rpcport=9266
rpcuser="bitmarkrpc"
rpcpassword="KfGnOWLCN48furQgfHuljO9IHB1QWQwC"
rpcheaders = {'content-type': "application/json", 'cache-control': "no-cache"}

def mark(marking):

    fee = marking["fee"]
    fee += 1
    print('mark with fee '+str(fee))
    marking["fee"] = fee
    rpcdata = {"jsonrpc":"1.0","id":"pythoncgi","method":"mark","params":[marking]}
    rpcdatadump = json.dumps(rpcdata)
    rpcurl="http://"+rpchost+":"+str(rpcport)
    while True:
        rpcresponse = requests.post(url=rpcurl,data=rpcdatadump, headers=rpcheaders, auth=(rpcuser,rpcpassword))
        jsonresponse = rpcresponse.json()
        if jsonresponse['error'] == None:
            txid = jsonresponse['result']
            print('txid: '+txid)
            rpcdata2 = {"jsonrpc":"1.0","id":"pythoncgi","method":"gettransaction","params":[txid]}
            rpcdatadump2 = json.dumps(rpcdata2)
            confirmed = False
            error = False
            while True:
                rpcresponse2 = requests.post(url=rpcurl,data=rpcdatadump2,headers=rpcheaders,auth=(rpcuser,rpcpassword))
                jsonresponse2 = rpcresponse2.json()
                if jsonresponse2['error'] == None:
                    nconfs = 0
                    if 'result' in jsonresponse2:
                        result2 = jsonresponse2['result']
                        if 'confirmations' in result2:
                            nconfs = result2['confirmations']
                    else:
                        print('Error: '+rpcresponse2.text)
                        error = True
                        break
                    print('nconfs = '+str(nconfs))
                    if nconfs >= 1:
                        confirmed = True
                        break
                    elif nconfs < 0:
                        break
                else:
                    print('Error: '+rpcresponse2.text)
                    error = True
                    break
                time.sleep(30)
            if confirmed or error:
                break
        else:
            print('Error: '+rpcresponse.text)
            break        
        time.sleep(2)

btih = sys.argv[1]
desctext = sys.argv[2]

marking={}
marking["hash"] = {}
marking["link"] = {}
markinghash = marking["hash"]
markinghash["type"] = "sha1"
markinghash["hex"] = btih
markinglink = marking["link"]
markinglink["protocol"] = "bt"
markinglink["host"] = "tracker_plx_im"
markinglink["port"] = "6969"
markinglink["path"] = ""
markinglink["cert_hash"] = {}
markinglinkcerthash = markinglink["cert_hash"]
markinglinkcerthash["type"] = ""
markinglinkcerthash["hex"] = ""
marking["fee"] = 1000
mark(marking)

marking2 = {}
marking2["hash"] = markinghash
marking2["desc"] = {}
marking2desc = marking2["desc"]
marking2desc["lang"] = ""
marking2desc["text"] = desctext
marking2["fee"] = 1000
mark(marking2)
