Beispiel #1
0
def index():

    bitcoind = bitcoinrpc.connect_to_local()
    balance = bitcoind.getbalance('')
    if balance < Decimal('2'):
        return render_template("base.html", balance=False)

    if request.method == 'GET':
        form = MyForm()

    elif request.method == 'POST':

        form = MyForm(request.form)
        if form.validate():
            
            result, amount = send_to_address(form.data.get("address"))
            
            add_transaction_to_database(form.data.get("address"), float(amount), request.remote_addr, result)
            return render_template('success.html', result=result, amount=amount)

    template_data = {
        "form": form,
        "balance": True,
    }

    return render_template("base.html", **template_data)
Beispiel #2
0
    def CheckForNewConfirmations(self):
        conn = bitcoinrpc.connect_to_local()
        for loctx in Transaction.objects.filter(confirmations__lt = 100, transactionType='receive'):
            if AccountFund.objects.get(id=loctx.fundIdIn).currencyCode=='BTC':
                tx = conn.gettransaction(loctx.ccTxId)
                timeSince = datetime.utcnow().replace(tzinfo=utc) - loctx.timeStamp

                if loctx.confirmations != tx.confirmations:
                    try:
                        with transaction.commit_on_success():
                            old = loctx.confirmations
                            loctx.confirmations=tx.confirmations
                            FundDataHelpers.RecalculateFunds(loctx, old)
                            loctx.problemFlag = False
                            loctx.flagReason = ''
                            loctx.save()
                    except Exception as e:
                        transaction.rollback()
                        logger.error('Could not save confimration update on: '+loctx.id)


                elif timeSince > timedelta(hours=24) and loctx.confirmations < 50:
                    loctx.problemFlag = True
                    loctx.flagReason = timeSince.seconds/3600+' hours since seen. Only '+loctx.confirmations+' confirmations.'
                    logger.error(loctx.flagReason)
                    loctx.save()
Beispiel #3
0
def run():
  conn = bitcoinrpc.connect_to_local()
  info = conn.getinfo()
  print "Blockcount:  %i" % info.blocks
  print "Connections: %i" % info.connections
  print "Difficulty:  %f" % info.difficulty

  for ac in conn.listaccounts():
    print
    bal = conn.getbalance(ac)
    print "Account: '%s'. Balance: %s" % (ac, bal)
    txs = conn.listtransactions(ac)
    for tx in txs:
      txid = tx.txid
      print "transaction:", tx.amount, "to", tx.address, "|", txid

  print
  print "Multisig 2 of 3:",
  #t = conn.proxy.listunspent()
  #print t
  multisig = gen_2of3(conn, "mrvQxKbe321W58xaTs65YS6mvUVGQyP52B", \
    "03b08df6e673619b93fc0dd39be70d7bf56873241fcfde9e87332d79b87de80fcd", "023d7a2768855435b221003cb23f26d950a4ee22f3d47c9833778326d221253afc")
  print multisig

  print
  print "RECIEVED?"
  check = check_rcv_2of3(conn, multisig, 0.1, searchdepth = 100)
  print check
  if not check[0]:
    print "ERROR: didn't received payment at %s" % multisig
    return

  print
  target_addr = "myKPhLdmfk6Ss8j6ugqCVwsC3bcUHpZCg5"
  amount = 0.1
  print "RELEASE %s BTC to %s" % (amount, target_addr)
  _, txid, voutid = check
  partial_tx = gen_partial_tx(conn, target_addr, txid, voutid, amount)
  print partial_tx

  print
  print "SIGNING RAW TX"
  # by default, uses all available private keys
  signed_partial_tx = sign_rawtx(conn, partial_tx)
  print signed_partial_tx

  print
  fn = "qr.png"
  print "GENERATING QR CODE for partial transaction: %s" % fn
  import qrencode as qr
  qrdata = signed_partial_tx.decode("hex").encode("base64")
  qrcode = qr.encode_scaled(qrdata, 512)
  qrcode[2].save(fn, format="png")

  print
  server_url = "http://10.200.1.73/multisig"
  order_id = "123"
  order_descr = "test bestellung 123"
  uri = gen_uri(server_url, order_id, order_descr)
  print "URI:", uri
Beispiel #4
0
def getRPCconn():
    USER=getpass.getuser()
    conn = bitcoinrpc.connect_to_local()
    try:
    	conn.getblockcount()
    except StandardError:
    	try:
            with open('/home/'+USER+'/.bitcoin/bitcoin.conf') as fp:
                RPCPORT="8332"
                RPCHOST="localhost"
                for line in fp:
                    #print line
                    if line.split('=')[0] == "rpcuser":
                    	RPCUSER=line.split('=')[1].strip()
                    elif line.split('=')[0] == "rpcpassword":
                    	RPCPASS=line.split('=')[1].strip()
                    elif line.split('=')[0] == "rpcconnect":
                    	RPCHOST=line.split('=')[1].strip()
                    elif line.split('=')[0] == "rpcport":
                    	RPCPORT=line.split('=')[1].strip()
		    elif line.split('=')[0] == "rpcssl":
                        if line.split('=')[1].strip() == "1":
			    RPCSSL="True"
			else:
			    RPCSSL="False"
    	except IOError as e:
            response='{"error": "Unable to load bitcoin config file. Please Notify Site Administrator"}'
            return response
        try:
            conn = bitcoinrpc.connect_to_remote(RPCUSER,RPCPASS,host=RPCHOST,port=RPCPORT,use_https=RPCSSL)
     	except StandardError:
            response='{"error": "Connection to bitcoind server unavailable. Please try agian in 5 minutes"}'
            return response
    return conn
Beispiel #5
0
    def init_app(self, app):
        """Set up this instance for use with *app*, if no app was passed to
        the constructor.
        """
        self.app = app
        app.coin_instance = self
        if not hasattr(app, 'extensions'):
            app.extensions = {}
        app.extensions['coin'] = self

        app.config.setdefault('COIN_RPC_URL', 'file:///tmp/bitcoin.conf')

        bits = urlparse(app.config['COIN_RPC_URL'])
        if bits.scheme == 'file':
            self.path = bits.path
            self.connection = connect_to_local(bits.path)
        else:
            hnp = None
            if '@' not in bits.netloc:
                raise ValueError("Refusing to connect to unauthenticated API endpoint")
            up, hnp = bits.netloc.rsplit('@', 1)
            self.username = up.split(':', 1)[0]
            self.password = up.split(':', 1)[-1]
            if ':' in hnp:
                self.hostname, port = hnp.split(':', 1)
                self.port = int(port)
            else:
                self.hostname = hnp
                self.port = 8332
            self.connection = connect_to_remote(self.username, self.password,
                                                host=self.hostname,
                                                port=self.port,
                                                use_https=bits.scheme == 'https')

        app.context_processor(_coin_context_processor)
 def handle(self, *args, **options):
     if BITCOINRPC_ARGS:
         conn = bitcoinrpc.connect_to_remote(*BITCOINRPC_ARGS['args'], **BITCOINRPC_ARGS['kwargs'])
     else:
         conn = bitcoinrpc.connect_to_local()
     for tx in conn.listtransactions():
         agentlib.store_btc_tx(tx)
Beispiel #7
0
def ew_exctract():
    rpc_connection = bitcoinrpc.connect_to_local()
    getinfo = rpc_connection.getinfo()
    print(getinfo)

    # block_hash = rpc_connection.getbestblockhash()
    # block_hash = "00000000000000000b664a85bce8dacc166bb9fcccad8ba3a644fb99407cf17c"
    block_hash = sys.argv[1]
    block = rpc_connection.getblock(block_hash)
    # print block
    result = {}
    ew_txs = []
    txs = block['tx']
    result['hash'] = block_hash
    result['height'] = block['height']
    result['time'] = block['time']
    for tx in txs:
        raw_tx = rpc_connection.getrawtransaction(tx)
        if "4557" in raw_tx:
            dectx = rpc_connection.decoderawtransaction(raw_tx)
            ew_txs.append(dectx)

    result['tx'] = ew_txs
    jsonresult = json.dumps(result, default=decimal_default)
    # print(jsonresult)

    conn = http.client.HTTPConnection('eternitywall.it', 80)
    conn.connect()
    conn.request('POST', "/v1/hooks/ewtx?hash=%s" % block_hash, jsonresult)
    resp = conn.getresponse()
    conn.close()
    print(resp.status, resp.reason)
Beispiel #8
0
def ew_exctract():
    rpc_connection = bitcoinrpc.connect_to_local()
    getinfo = rpc_connection.getinfo()
    print(getinfo)

    # block_hash = rpc_connection.getbestblockhash()
    # block_hash = "00000000000000000b664a85bce8dacc166bb9fcccad8ba3a644fb99407cf17c"
    block_hash = sys.argv[1]
    block = rpc_connection.getblock(block_hash)
    # print block
    result = {}
    ew_txs = []
    txs = block['tx']
    result['hash'] = block_hash
    result['height'] = block['height']
    result['time'] = block['time']
    for tx in txs:
        raw_tx = rpc_connection.getrawtransaction(tx)
        if "4557" in raw_tx:
            dectx = rpc_connection.decoderawtransaction(raw_tx)
            ew_txs.append(dectx)

    result['tx'] = ew_txs
    jsonresult = json.dumps(result, default=decimal_default)
    # print(jsonresult)

    conn = http.client.HTTPConnection('eternitywall.it', 80)
    conn.connect()
    conn.request('POST', "/v1/hooks/ewtx?hash=%s" % block_hash, jsonresult)
    resp = conn.getresponse()
    conn.close()
    print(resp.status, resp.reason)
Beispiel #9
0
def getRPCconn():
    USER=getpass.getuser()
    conn = bitcoinrpc.connect_to_local()
    try:
    	conn.getblockcount()
    except StandardError:
    	try:
            with open('/home/'+USER+'/.bitcoin/bitcoin.conf') as fp:
                RPCPORT="8332"
                RPCHOST="localhost"
                for line in fp:
                    #print line
                    if line.split('=')[0] == "rpcuser":
                    	RPCUSER=line.split('=')[1].strip()
                    elif line.split('=')[0] == "rpcpassword":
                    	RPCPASS=line.split('=')[1].strip()
                    elif line.split('=')[0] == "rpcconnect":
                    	RPCHOST=line.split('=')[1].strip()
                    elif line.split('=')[0] == "rpcport":
                    	RPCPORT=line.split('=')[1].strip()
		    elif line.split('=')[0] == "rpcssl":
                        if line.split('=')[1].strip() == "1":
			    RPCSSL="True"
			else:
			    RPCSSL="False"
    	except IOError as e:
            response='{"error": "Unable to load bitcoin config file. Please Notify Site Administrator"}'
            return response
        try:
            conn = bitcoinrpc.connect_to_remote(RPCUSER,RPCPASS,host=RPCHOST,port=RPCPORT,use_https=RPCSSL)
     	except StandardError:
            response='{"error": "Connection to bitcoind server unavailable. Please try agian in 5 minutes"}'
            return response
    return conn
Beispiel #10
0
    def validate_address(form, field):
        bitcoind = bitcoinrpc.connect_to_local()
        result = bitcoind.validateaddress(field.data)

        if not result.isvalid:
            raise ValidationError('invalid mmc address.')

        if not check_tx(request.remote_addr, field.data):
            raise ValidationError('try tomorrow.')
	def __init__(self, pps_rate, gh, y, btcusd = 0):
		self.pps_rate = pps_rate
		self.gh = gh
		self.conn = bitcoinrpc.connect_to_local()
		self.blockcount = self.conn.getblockcount()
		self.lastblock = self.getblock(self.blockcount)
		self.y = y
		self.btcusd = btcusd
		if btcusd <= 0: self.btcusd = self.get_btcusd()
Beispiel #12
0
def getRPCconn():
    USER=getpass.getuser()
    conn = bitcoinrpc.connect_to_local()
    try:
        conn.getblockcount()
    except StandardError:
        response='{"error": "Connection to bitcoind server unavailable. Please try agian in 5 minutes"}'
        return response
    return conn
Beispiel #13
0
def send_to_address(address):
    list1, list2, list3, list4 = random.uniform(0.01, 0.5), random.uniform(0.01, 0.2), random.uniform(0.01, 0.5), random.uniform(0.01, 2)
    all_ = [list1, list2, list3, list4]
    random.shuffle(all_)

    amount = Decimal(str(all_[0])[0:7])
    bitcoind = bitcoinrpc.connect_to_local()
    result = bitcoind.sendtoaddress(address, float(amount))

    return result, amount
Beispiel #14
0
 def __init__(self, settings):
     user = settings.get('bitcoin.user', '')
     password = settings.get('bitcoin.password', '')
     host = settings.get('bitcoin.host', 'localhost')
     port = settings.get('bitcoin.port', 8332)
     if user == '':
         self.rpc = bitcoinrpc.connect_to_local()
     else:
         self.rpc = bitcoinrpc.connect_to_remote(user, password, host, port)
     self.month_price = float(settings.get('bitcoin.month_price', 0.02))
     self.account = settings.get('bitcoin.account', 'ccvpn2')
Beispiel #15
0
 def __init__(self, settings):
     user = settings.get('bitcoin.user', '')
     password = settings.get('bitcoin.password', '')
     host = settings.get('bitcoin.host', 'localhost')
     port = settings.get('bitcoin.port', 8332)
     if user == '':
         self.rpc = bitcoinrpc.connect_to_local()
     else:
         self.rpc = bitcoinrpc.connect_to_remote(user, password, host, port)
     self.month_price = float(settings.get('bitcoin.month_price', 0.02))
     self.account = settings.get('bitcoin.account', 'ccvpn2')
def _connect():
    "Returns a new connection to the bitcoin daemon"
    if(settings.BITCOINRPC_CONN['remote']):
        user = settings.BITCOINRPC_CONN['user']
        password = settings.BITCOINRPC_CONN['password']
        host = settings.BITCOINRPC_CONN['host']
        port = settings.BITCOINRPC_CONN['port']
        use_https = settings.BITCOINRPC_CONN['use_https']
        return bitcoinrpc.connect_to_remote(user=user, password=password, host=host, port=port, use_https=use_https)
    else:
        return bitcoinrpc.connect_to_local()
Beispiel #17
0
 def getBTCRPC(self, settings):
     if not BitcoinMethod.rpc:
         user = settings.get('bitcoin.user', '')
         password = settings.get('bitcoin.password', '')
         host = settings.get('bitcoin.host', 'localhost')
         port = settings.get('bitcoin.port', 8332)
         if user == '':
             rpc = bitcoinrpc.connect_to_local()
         else:
             rpc = bitcoinrpc.connect_to_remote(user, password, host, port)
         BitcoinMethod.rpc = rpc
     return BitcoinMethod.rpc
Beispiel #18
0
def newAddress(nome): # Função para criação de um novo endereç Bitcoin ou retorno do endereço já criado
	bit = bitcoinrpc.connect_to_local()
	c,conn = dbConnect() # Conecta a database
	ex = c.execute('select address from users where nome = "%s"' % nome) # Procura o endeço do usuário
	address = ex.fetchone()
	address = address[0]
	if address == None: # Caso o usuário não tenha um endereço, criar.
		address = bit.getnewaddress(nome)
		c.execute('update users set address = "%s" where nome = "%s"' % (address,nome))
		conn.commit()
		return address
	else: # Caso tenha, apenas retorná-lo
		return address
Beispiel #19
0
def connectlocal(filename=None):
    """
    Connect to default coin service instance owned by this user,
    on this machine.

    @type filename: string
    @param filename: Path to a configuration file in a non-standard
    location (optional).
    """
    global conn
    conn = bitcoinrpc.connect_to_local(filename)
    resp = jsonify(code="1000", message=settings.OK_1000)
    resp.status_code = 200
    return resp
def _connect():
    "Returns a new connection to the bitcoin daemon"
    if settings.BITCOINRPC_CONN['remote']:
        user = settings.BITCOINRPC_CONN['user']
        password = settings.BITCOINRPC_CONN['password']
        host = settings.BITCOINRPC_CONN['host']
        port = settings.BITCOINRPC_CONN['port']
        use_https = settings.BITCOINRPC_CONN['use_https']
        return bitcoinrpc.connect_to_remote(user=user,
                                            password=password,
                                            host=host,
                                            port=port,
                                            use_https=use_https)
    else:
        return bitcoinrpc.connect_to_local()
    def __init__(self):
        if BITCOINRPC_ARGS:
            self.rpcconn = bitcoinrpc.connect_to_remote(*BITCOINRPC_ARGS['args'],
                                                        **BITCOINRPC_ARGS['kwargs'])
        else:
            self.rpcconn = bitcoinrpc.connect_to_local()
        print "Bitcoind URL: %s" % self.rpcconn.url
        mqparam = pika.connection.URLParameters(settings.BITCOIN_QUEUE_URL)
        print settings.BITCOIN_QUEUE_URL
        self.mqconn = pika.BlockingConnection(mqparam)
        self.channel = self.mqconn.channel()
        self.channel.queue_declare(queue='bitcoind_rpc',
                                   durable=True)
#         self.channel.queue_declare(queue='bitcoind_cast',
#                                    durable=True)
        self.channel.basic_qos(prefetch_count=1)
        self.channel.basic_consume(self._rpc_callback, queue='bitcoind_rpc')
Beispiel #22
0
def show_form():
    form = OrderForm()

    if form.validate_on_submit():
        bitcoin = bitcoinrpc.connect_to_local()
        order = Order().populate_from_order_form(form)
        order.address = bitcoin.getnewaddress()
        db.session.add(order)
        
        for gb_form in form.group_buys:
            db.session.add(GroupBuy(order = order
                ).populate_from_groupbuy_form(gb_form))
        
        db.session.commit()
        
        return redirect(url_for(".order_completed", address = order.address))
    
    return render_template("index.html",
        form = form, prices = prices, site_name = app.config["SITE_NAME"])
Beispiel #23
0
    def init_app(self, app):
        """Set up this instance for use with *app*, if no app was passed to
        the constructor.
        """
        self.app = app
        app.coin_instance = self
        if not hasattr(app, 'extensions'):
            app.extensions = {}
        app.extensions['coin'] = self

        app.config.setdefault('COIN_RPC_URL', 'file:///tmp/bitcoin.conf')

        bits = urlparse(app.config['COIN_RPC_URL'])
        if bits.scheme == 'file':
            self.path = bits.path
            self.connection = connect_to_local(bits.path)
        else:
            hnp = None
            if '@' not in bits.netloc:
                raise ValueError(
                    "Refusing to connect to unauthenticated API endpoint")
            up, hnp = bits.netloc.rsplit('@', 1)
            self.username = up.split(':', 1)[0]
            self.password = up.split(':', 1)[-1]
            if ':' in hnp:
                self.hostname, port = hnp.split(':', 1)
                self.port = int(port)
            else:
                self.hostname = hnp
                self.port = 8332
            self.connection = connect_to_remote(
                self.username,
                self.password,
                host=self.hostname,
                port=self.port,
                use_https=bits.scheme == 'https')

        app.context_processor(_coin_context_processor)
    def handle(self, *args, **options):
        try:
            if BITCOINRPC_ARGS:
                conn = bitcoinrpc.connect_to_remote(*BITCOINRPC_ARGS['args'], **BITCOINRPC_ARGS['kwargs'])
            else:
                conn = bitcoinrpc.connect_to_local()
        except Exception as e:
            print "Could not connect to bitcoind."
            print "%s: %s" % (e.__class__, e)
            sys.exit(1)
        poll_transactions(conn, 50)
        expire_time = next_timeout(5)
        try:
            while True:
                poll_transactions(conn, 5)
                time.sleep(1)
                if int(time.time()) > expire_time:
                    expire_time = next_timeout(3600)
                    print "=========== %s ===========" % datetime.datetime.now()
#                     objgraph.show_most_common_types(limit=5)
#                  print "Tick..."
        except KeyboardInterrupt:
            print "Keyboard interrupt received.  Exiting."
Beispiel #25
0
def init(username, password, host, port='8332', local=False, configfile=os.path.expanduser('~/.bitcoin/bitcoin.conf')):
    """
    Check bitcoinrpc is installed and create connection to BitCoin server - local or remote
    """
    if not installed():
        dhnio.Dprint(4, 'bitcoin.init WARNING module bitcoin-python is not installed, skip.')
        return
    dhnio.Dprint(4, 'bitcoin.init')
    global _Connection
    if _Connection is None:
        try:
            if local:
                if os.path.isfile(configfile):
                    dhnio.Dprint(4, 'bitcoin.init calling connect_to_local, config file is %s ' % configfile)
                    _Connection = bitcoinrpc.connect_to_local(configfile)
                else:
                    dhnio.Dprint(4, 'bitcoin.init ERROR config file %s not exist' % configfile)
            else:
                dhnio.Dprint(4, 'bitcoin.init calling connect_to_remote, args: %s' % str((username, password, host, port)))
                _Connection = bitcoinrpc.connect_to_remote(username, password, host, port)
        except Exception, e:
            dhnio.Dprint(4, 'bitcoin.init ERROR initializing connection: %s' % str(e))
            return
Beispiel #26
0
    def SearchForNewBTCTransactions(self):

        '''
        logging.basicConfig(stream=sys.stdout, level=logging.INFO,
                            datefmt="%Y-%m-%d %H:%M:%S",
                            format="[%(asctime)-15s] %(message)s")
        '''

        logger.info("Checking for new transaction data...")
        conn = bitcoinrpc.connect_to_local()
        for fund in AccountFund.objects.filter(currencyCode='BTC'):

            actualIn = BtcAPIInterface.getTotalReceived(conn, fund.fundAddress)

            transactions = BtcAPIInterface.getLastTransactions(conn, fund.fundAddress, fund.numTransactionsSeen)
            noSeen = self.WorkTroughNewTransactions(transactions, fund)

            if len(transactions)==noSeen:
                fund.numTransactionsSeen+=noSeen

            fund.totalIn=actualIn

            fund.save()
Beispiel #27
0
def saque(data): # Função de saque
	bit = bitcoinrpc.connect_to_local() # Conecta a carteira local 
	c,conn = dbConnect() # Conecta a database
	if len(data) != 4: # Verifica se o comando está completo
		return 'Uso inadequado do comando.'
	try: # Verifica se o comando está correto
		qntBTC = float(data[1])
	except ValueError:
		return 'Uso inadequado do comando.'
	address = data[2]
	val = bit.validateaddress(address) # Checa se o endereço é válido
	if not val.isvalid:
		return 'Endereço inválido'
	# Caso tudo esteja correto, entra na função:
	nome = data[3]
	ex = c.execute('select btc from users where nome = "%s"'%(nome)) # Obtém o saldo do usuário
	ex = ex.fetchone()[0]
	if (ex-0.0002) < qntBTC:
		return 'Saldo insuficiente'
	else: # Caso o usuário tenha saldo suficiente, enviar para a conta e retirar do saldo
		bit.sendtoaddress(address,qntBTC)
		c.execute('update users set btc = btc - %.8f where nome = "%s"'%(qntBTC+0.0002,nome))
		conn.commit()
		return 'Saque realizado com sucesso.'
Beispiel #28
0
def decode(rawhex, reference):

  #sort out whether using local or remote API
  conn = bitcoinrpc.connect_to_local()
  #conn = bitcoinrpc.connect_to_remote('btcrpc_username','btcrpc_secret',host='127.0.0.1', port=8332)

  rawBTC = conn.decoderawtransaction(rawhex)

  if reference == "":
    retval = {"Error":"Can\'t decode MP TX. No valid sending address found."}
    return {'Sender':reference,'BTC':rawBTC, 'MP':retval}

  #get all multisigs
  multisig_output = []
  dest=""
  for output in rawBTC['vout']:
    if output['scriptPubKey']['type'] == 'multisig':
      multisig_output.append(output) #grab msigs
    elif output['scriptPubKey']['type'] in ['pubkeyhash','scripthash']:
      try:
        for address in output['scriptPubKey']['addresses']:
          if address not in ['1EXoDusjGwvnjZUyKkxZ4UHEf77z6A5S4P','mpexoDuSkGGqvqrkrjiFng38QPkJQVFyqv'] and address not in reference:
            dest=address
            #return on first successful dest address per spec (highest vout)
            break
      except KeyError:
        pass

  #extract compressed keys
  scriptkeys = []
  for output in multisig_output:   #seqnums start at 1, so adjust range
    split_script = output['scriptPubKey']['asm'].split(' ')
    for val in split_script:
        if len(val) == 66:
            scriptkeys.append(val)

  #filter keys that are ref
  nonrefkeys = []

  #check for testnet addresses
  if reference[:1] in ['2','m','n']:
    #testnet address
    offset=111
  else:
    offset=0

  for compressedkey in scriptkeys:
    if pybitcointools.pubtoaddr(compressedkey,offset) not in reference :
        nonrefkeys.append(compressedkey)

  max_seqnum = len(nonrefkeys)
  sha_keys = [ hashlib.sha256(reference).digest().encode('hex').upper()]  #first sha256 of ref addr, see class B for more info
  for i in range(max_seqnum):
    if i < (max_seqnum-1):
        sha_keys.append(hashlib.sha256(sha_keys[i]).digest().encode('hex').upper()) #keep sha'ing to generate more packets

  pairs = []
  for i in range(len(nonrefkeys)):
    pairs.append((nonrefkeys[i], sha_keys[i] ))

  packets = []
  for pair in pairs:
    obpacket = pair[0].upper()[2:-2]
    shaaddress = pair[1][:-2]
    print 'Obfus/SHA', obpacket, shaaddress
    datapacket = ''
    for i in range(len(obpacket)):
        if obpacket[i] == shaaddress[i]:
            datapacket = datapacket + '0'
        else:
            bin_ob = int('0x' + obpacket[i], 16)
            bin_sha = int('0x' + shaaddress[i], 16)
            xored = hex(bin_ob ^ bin_sha)[2:].upper()
            datapacket = datapacket + xored
    packets.append(datapacket)

  long_packet = ''
  for packet in packets:
    print 'Decoded packet #' + str(packet[0:2]) + ' : ' + packet
    long_packet += packet[2:]

  retval=""
  #DEBUG print long_packet[4:8]

  if long_packet[4:8] == '0032':
    #Create Fixed Issuance
    spare_bytes = ''.join(long_packet[22:])
    #DEBUG print spare_bytes.split('00')
    len_var_fields = len(''.join(spare_bytes.split('00')[0:5])+'0000000000')
    #DEBUG print len_var_fields, spare_bytes[len_var_fields:len_var_fields+16],spare_bytes

    retval = { 'TxVersion': int(long_packet[0:4],16),
               'TxType': int(long_packet[4:8],16),
               'TxTypeString': 'Create Fixed Issuance',
               'Ecosystem': int(long_packet[8:10],16),
               'Property Type': int(long_packet[10:14],16),
               'Previous Property ID': int(long_packet[14:22],16),
               'Property Category': spare_bytes.split('00')[0].decode('hex'),
               'Property Subcategory': spare_bytes.split('00')[1].decode('hex'),
               'Property Name': spare_bytes.split('00')[2].decode('hex'),
               'Property URL':  spare_bytes.split('00')[3].decode('hex'),
               'Property Data':  ''.join(spare_bytes.split('00')[4]).decode('hex'),
               'Number of Properties: ': int(str(int(spare_bytes[len_var_fields:len_var_fields+16],16)))
             }

  if long_packet[4:8] == '0033':
    #Create Variable issuance (Crowdsale)
    spare_bytes = ''.join(long_packet[22:])
    #DEBUG print spare_bytes.split('00')
    len_var_fields = len(''.join(spare_bytes.split('00')[0:5])+'0000000000')
    #DEBUG print len_var_fields, spare_bytes[len_var_fields:len_var_fields+16],spare_bytes

    retval = { 'TxVersion': int(long_packet[0:4],16),
               'TxType': int(long_packet[4:8],16),
               'TxTypeString': 'Create Variable Issuance (Crowdsale)',
               'Ecosystem': int(long_packet[8:10],16),
               'Property Type': int(long_packet[10:14],16),
               'Previous Property ID': int(long_packet[14:22],16),
               'Property Category': spare_bytes.split('00')[0].decode('hex'),
               'Property Subcategory': spare_bytes.split('00')[1].decode('hex'),
               'Property Name': spare_bytes.split('00')[2].decode('hex'),
               'Property URL':  spare_bytes.split('00')[3].decode('hex'),
               'Property Data':  ''.join(spare_bytes.split('00')[4]).decode('hex'),
               'PropertyID Desired': str(int(spare_bytes[len_var_fields:len_var_fields+8],16)),
               'Number of Properties': str(int(spare_bytes[len_var_fields+8:len_var_fields+8+16],16)),
               'Deadline': str(int(spare_bytes[len_var_fields+8+16:len_var_fields+8+16+16],16)),
               'Earlybird Bonus': str(int(spare_bytes[len_var_fields+8+16+16:len_var_fields+8+16+16+2],16)),
               'Percentage for Issuer': str(int(spare_bytes[len_var_fields+8+16+16+2:len_var_fields+8+16+16+2+2],16))
             }

  if long_packet[4:8] == '0000':
    #simple send
    retval = { 'TxVersion': int(long_packet[0:4],16),
               'TxType': int(long_packet[4:8],16),
               'TxTypeString': 'Simple Send',
               'PropertyID': int(long_packet[8:16],16),
               'Amount': int(long_packet[16:32],16)
             }

  if long_packet[4:8] == '0003':
    #STO
    retval = { 'TxVersion': int(long_packet[0:4],16),
               'TxType': int(long_packet[4:8],16),
               'TxTypeString': 'Send To Owners',
               'PropertyID': int(long_packet[8:16],16),
               'Amount': int(long_packet[16:32],16)
             }

  if long_packet[4:8] == '0014':
    #DEx Sell Offer
    retval = { 'TxVersion': int(long_packet[0:4],16),
               'TxType': int(long_packet[4:8],16),
               'TxTypeString': 'DEx Sell Offer',
               'PropertyID': int(long_packet[8:16],16),
               'Amount': int(long_packet[16:32],16),
               'BTCDesired': int(long_packet[32:48],16),
               'TimePeriod': int(long_packet[48:50],16),
               'FeeRequired': int(long_packet[50:66],16),
               'Action': int(long_packet[66:68],16)
             }

  if long_packet[4:8] == '0035':
    #Close Crowdsale Manually
    retval = { 'TxVersion': int(long_packet[0:4],16),
               'TxType': int(long_packet[4:8],16),
               'TxTypeString': 'Close Crowdsale Manually',
               'PropertyID': int(long_packet[8:16],16)
             }

  if long_packet[4:8] == '0036':
    #grant properties
    #Create Fixed Issuance
    spare_bytes = ''.join(long_packet[22:])
    #DEBUG print spare_bytes.split('00')
    len_var_fields = len(''.join(spare_bytes.split('00')[0:5])+'0000000000')
    #DEBUG print len_var_fields, spare_bytes[len_var_fields:len_var_fields+16],spare_bytes

    retval = { 'TxVersion': int(long_packet[0:4],16),
               'TxType': int(long_packet[4:8],16),
               'TxTypeString': 'Create New Grant Property',
               'Ecosystem': int(long_packet[8:10],16),
               'Property Type': int(long_packet[10:14],16),
               'Previous Property ID': int(long_packet[14:22],16),
               'Property Category': spare_bytes.split('00')[0].decode('hex'),
               'Property Subcategory': spare_bytes.split('00')[1].decode('hex'),
               'Property Name': spare_bytes.split('00')[2].decode('hex'),
               'Property URL':  spare_bytes.split('00')[3].decode('hex'),
               'Property Data':  ''.join(spare_bytes.split('00')[4]).decode('hex')
             }
             #'Number of Properties: ': int(str(int(spare_bytes[len_var_fields:len_var_fields+16],16)))

  if long_packet[4:8] == '0037':
    #grant properties
    retval = { 'TxVersion': int(long_packet[0:4],16),
               'TxType': int(long_packet[4:8],16),
               'TxTypeString': 'Grant Properties',
               'PropertyID': int(long_packet[8:16],16),
               'Amount': int(long_packet[16:32],16)
             }

  if long_packet[4:8] == '0038':
    #revoke properties
    retval = { 'TxVersion': int(long_packet[0:4],16),
               'TxType': int(long_packet[4:8],16),
               'TxTypeString': 'Revoke Properties',
               'PropertyID': int(long_packet[8:16],16),
               'Amount': int(long_packet[16:32],16)
             }

  if retval == "":
    retval = {"Error":"Can\'t decode MP TX"}
    dest = ""
  retval['sender']=reference
  retval['recipient']=dest

  print json.dumps(retval, indent=2)
Beispiel #29
0
def get_bitcoin_conn():
    """Gets a connection to the Bitcoin wallet."""
    try:
        return bitcoin.connect_to_local()
    except:
        raise errors.BitcoinConnectionError()
def run_P2SH_sign():
  if len(sys.argv) < 2: 
      exit()

  force=False

  if sys.argv[1] == '-ui':
    import CLI_prompter_P2SH_signer
    listOptions = CLI_prompter_P2SH_signer.callCLI()
  else:
    listOptions = { 
            'unsignedhex': sys.argv[1], 
            'spending_input': sys.argv[2],
            "spending_input_vout": int(sys.argv[3]),
            "p2sh_addr_pubkey": sys.argv[4],     #scriptpubkey
            "p2sh_redeemscript": sys.argv[5],         #p2sh redeemscript
            "privkey": sys.argv[6],                   #privkey to sign with
            "testnet": bool(int(sys.argv[7])) #0 or 1
        }

  HEXSPACE_SECOND='21'

  if listOptions['testnet']:
      testnet=True
      magicbyte=111
  else:
      testnet=False
      magicbyte=0

  if sys.argv[1] == '-ui':
    if listOptions['conndetails'][0] == 'local':
      conn = bitcoinrpc.connect_to_local()
    elif listOptions['conndetails'][0] == 'remote':
      conndetails=open( listOptions['conndetails'][1] ).readline().split(':')
      conn = bitcoinrpc.connect_to_remote(conndetails[0],conndetails[1],host=conndetails[2],port=int(conndetails[3]),use_https=int(conndetails[4]))
    else:
      print 'connection did not establish: FAIL'
      exit()
  else:
    if sys.argv[8] == 'local':
      conn = bitcoinrpc.connect_to_local()
    elif sys.argv[8] == 'remote':
      conndetails=open(sys.argv[9]).readline().split(':')
      #print conndetails, int(conndetails[4])
      #sort out whether using local or remote API
      conn = bitcoinrpc.connect_to_remote(conndetails[0],conndetails[1],host=conndetails[2],port=int(conndetails[3]),use_https=int(conndetails[4]))
    else:
      print 'connection did not establish: FAIL'
      exit()

  #decode unsigned hex to get input spend (only take 1 at a time i guess)
  #get raw on input, as well as vout
  #using input find p2sh output and get redeemscript
  #redeemscript probably needs to be provided
  #privkey too

  partial_signed_raw_tx = conn.signrawtransaction(listOptions['unsignedhex'], [ { 'txid': listOptions['spending_input'], 'vout': listOptions['spending_input_vout'], 'scriptPubKey': listOptions['p2sh_addr_pubkey'], 'redeemScript': listOptions['p2sh_redeemscript'] } ], [ listOptions['privkey'] ] )

  hex_transaction = partial_signed_raw_tx['hex']
  #verify that transaction is valid
  assert type(conn.decoderawtransaction(''.join(hex_transaction).lower())) == type({})

  #dump unsigned
  if sys.argv[1] == '-ui':
    #dump unsigned
    print ''
    if partial_signed_raw_tx['complete'] == False: print "WARNING: YOUR TRANSACTION IS NOT YET COMPLETELY SIGNED, MAKE SURE YOU SIGN IT WITH ALL REQUIRED ADDRESSES BEFORE TRANSMITTING."
    if partial_signed_raw_tx['complete'] == True: print "SUCCESS: YOUR TRANSACTION IS COMPLETELY SIGNED, GOOD WORK BUDDY."
    print 'This is your hex, buddy: '
    print ''.join(hex_transaction)
    print ''
    if partial_signed_raw_tx['complete'] == False:
      sign_it=raw_input('Would you like to sign it again? [yes OR no]')
      if sign_it == 'yes':
         run_P2SH_sign()
      else: exit()
  else:
    print ''.join(hex_transaction)
Beispiel #31
0
def get_bitcoin_conn():
    """Gets a connection to the Bitcoin wallet."""
    try:
        return bitcoin.connect_to_local()
    except:
        raise errors.BitcoinConnectionError()
Beispiel #32
0
#payout script, pays all of user bets
'''
parlay bets are saved as single bets(including ammount), but not paid out as single bets, so this is probably not a problem

I use decimal odds - 3.4 means that if you bet 1, you get 3.4


do logic like if offer.match=open, can't payout. if offer.match=closed and offer.result=None (tie), they get back 1
'''
from models import *
import bitcoinrpc as b
c=b.connect_to_local()

admin='admin'
def payout():
    #pay
    offers=Offer.objects.filter(result=True)
    for o in offers:
        succesful_bets=Bet.objects.filter(submitted=True,offer=o)
        for sb in succesful_bets:
            if sb.parlay==False and sb.paid==False:
               user=str(sb.user)
               odds=o.odds
               amt=odds*(sb.amt/1000)
               c.move(admin,user,amt)
               sb.paid=True
               sb.save()
    parlays=Parlay.objects.filter(paid=False)
    for p in parlays:
        sol=False
        parlay_amt=p.amt/1000
Beispiel #33
0
    def handle_annotate(abe, page):
        tx_hash = (page['params'].get('tx') or [''])[0]
        address = (page['params'].get('address') or [''])[0]
        message = (page['params'].get('comment') or [''])[0]
        signature = (page['params'].get('signature') or [''])[0]

        if not tx_hash and not address:
            page['title'] = 'Annotations'
            page['body'] += [
                'This website allows you to annotate the Bitcoin blockchain.<br/><br/>',
                'You will need a version of bitcoind that has the "signmessage" command.<br/>'
                'In order to annotate an address or transaction, first <a href="search">find</a> the corresponding page, then follow the "[+]" link. <a href="http://ecdsa.org/annotate?tx=e357fece18a4191be8236570c7dc309ec6ac04473317320b5e8b9ab7cd023549">(example here)</a><br/><br/>'
            ]

            page['body'] += ['<h3>Annotated addresses.</h3>']
            rows = abe.store.selectall(
                """select text, address from addr_comments limit 100""")
            page['body'] += ['<table>']
            page['body'] += ['<tr><th>Address</th><th>Comment</th></tr>']
            for row in rows:
                link = '<a href="address/' + row[1] + '">' + row[1] + '</a>'
                page['body'] += [
                    '<tr><td>' + link + '</td><td>' + row[0] + '</td></tr>'
                ]
            page['body'] += ['</table>']

            page['body'] += ['<h3>Annotated transactions.</h3>']
            rows = abe.store.selectall(
                """select tx.tx_id, tx.tx_hash, comments.c_text 
                                          from comments left join tx on tx.tx_id = comments.c_tx where c_sig != '' limit 100"""
            )
            page['body'] += ['<table>']
            page['body'] += ['<tr><th>Transaction</th><th>Comment</th></tr>']
            for row in rows:
                link = '<a href="tx/' + row[1] + '">' + row[1] + '</a>'
                page['body'] += [
                    '<tr><td>' + link + '</td><td>' + row[2] + '</td></tr>'
                ]
            page['body'] += ['</table>']
            return

        if tx_hash:

            page['title'] = 'Annotate transaction'
            tx_id, b, c, d, e, f = abe.get_tx(tx_hash)
            chain = abe.get_default_chain()

            in_addresses = []
            for row in abe.get_tx_inputs(tx_id):
                addr = abe.store.binout(row[6])
                addr = hash_to_address_link(chain['address_version'], addr,
                                            '../')
                in_addresses.append(addr[3])
            if not address:
                address = in_addresses[0]

            out_addresses = []
            for row in abe.get_tx_outputs(tx_id):
                addr = abe.store.binout(row[6])
                addr = hash_to_address_link(chain['address_version'], addr,
                                            '../')
                out_addresses.append(addr[3])

            if message or signature:
                # check address
                #if address not in in_addresses and address not in out_addresses:
                if address not in in_addresses:
                    page['title'] = 'Error'
                    page['body'] = [
                        '<p>wrong address for this transaction.</p>\n'
                    ]
                    print address, in_addresses
                    return

                # check signature
                import bitcoinrpc
                conn = bitcoinrpc.connect_to_local()
                message = message.replace("\r\n",
                                          "\\n").replace("!", "\\!").replace(
                                              "$", "\\$")
                print "verifymessage:", address, signature, repr(message)
                try:
                    v = conn.verifymessage(address, signature,
                                           tx_hash + ":" + message)
                except:
                    v = False
                if not v:
                    page['title'] = 'Error'
                    page['body'] = ['<p>Invalid signature.</p>']
                    return

                # little bobby tables
                message = message.replace('"', '\\"').replace("'", "\\'")
                # escape html
                message = escape(message)
                message = message[:1024]

                row = abe.store.selectrow(
                    "select c_tx from comments where c_tx=%d " % (tx_id))
                if not row:
                    abe.store.sql(
                        "insert into comments (c_tx, c_text, c_pubkey, c_sig) VALUES (%d, '%s', '%s', '%s')"
                        % (tx_id, message, address, signature))
                    abe.store.commit()
                    page['body'] = [
                        '<p>Your comment was added successfully.</p>\n'
                    ]
                else:
                    if not message:
                        abe.store.sql("delete from comments where c_tx=%d " %
                                      (tx_id))
                        abe.store.commit()
                        page['body'] = ['<p>Your comment was deleted.</p>\n']
                    else:
                        abe.store.sql(
                            "update comments set c_text='%s', c_sig='%s', c_pubkey='%s' where c_tx=%d "
                            % (message, signature, address, tx_id))
                        abe.store.commit()
                        page['body'] = ['<p>Your comment was updated.</p>\n']
                return
            else:
                select = "<select id=\"address\" onkeyup=\"change_address(this.value);\" onchange=\"change_address(this.value);\" name='address'>" \
                    + "\n".join( map( lambda addr: "<option value=\""+addr+"\">"+addr+"</option>", in_addresses ) ) \
                    +"</select>"
                select = select.replace(
                    "<option value=\"" + address + "\">",
                    "<option value=\"" + address + "\" selected>")
                tx_link = '<a href="tx/' + tx_hash + '">' + tx_hash + '</a>'

                javascript = """
            <script>
               function change_address(x){ 
                 document.getElementById("saddress").innerHTML=x;
               }
               function change_text(x){ 
                 x = x.replace(/!/g,"\\\\!");
                 x = x.replace(/\\n/g,"\\\\n");
                 x = x.replace(/\\$/g,"\\\\$");
                 document.getElementById("stext").innerHTML = x; 
               }
               function onload(){
                 change_text(document.getElementById("text").value);
                 //change_address(document.getElementById("address").value);
               }
            </script>
            """

                page['title'] = 'Annotate transaction'
                page['body'] = [
                    javascript, '<form id="form" action="', page['dotdot'],
                    'annotate">\n'
                    'Transaction: ', tx_link, '<br/>'
                    'Address:', select, '<br/><br/>\n'
                    'Message:<br/><textarea id="text" onkeyup="change_text(this.value);" name="comment" cols="80" value=""></textarea><br/><br/>\n'
                    'You must sign your message with one of the input addresses of involved in the transaction.<br/>\n'
                    'The signature will be returned by the following command line:<br/>\n'
                    '<pre>bitcoind signmessage <span id="saddress">' +
                    in_addresses[0] + '</span> "' + tx_hash +
                    ':<span id="stext">your text</span>"</pre>\n'
                    'Signature:<br/><input name="signature" value="" style="width:500px;"/><br/>'
                    '<input name="tx" type="hidden" value="' + tx_hash + '" />'
                    '<button type="submit">Submit</button>\n'
                    '</form>\n'
                ]
            return

        if address:
            page['title'] = 'Annotate address'

            if message or signature:
                # check signature
                import bitcoinrpc
                conn = bitcoinrpc.connect_to_local()
                message = message.replace("\n", "\\n").replace("!",
                                                               "\\!").replace(
                                                                   "$", "\\$")
                print "verifymessage:", address, signature, message
                try:
                    v = conn.verifymessage(address, signature, message)
                except:
                    v = False
                if not v:
                    page['title'] = 'Error'
                    page['body'] = ['<p>Invalid signature.</p>']
                    return

                # little bobby tables
                message = message.replace('"', '\\"').replace("'", "\\'")
                # escape html
                message = escape(message)
                message = message[:1024]

                row = abe.store.selectrow(
                    "select address from addr_comments where address='%s' " %
                    (address))
                if not row:
                    abe.store.sql(
                        "insert into addr_comments (address, text) VALUES ('%s', '%s')"
                        % (address, message))
                    abe.store.commit()
                    page['body'] = [
                        '<p>Your comment was added successfully.</p>\n'
                    ]
                else:
                    if not message:
                        abe.store.sql(
                            "delete from addr_comments where address='%s' " %
                            (message))
                        abe.store.commit()
                        page['body'] = ['<p>Your comment was deleted.</p>\n']
                    else:
                        abe.store.sql(
                            "update addr_comments set text='%s' where address='%s' "
                            % (message, address))
                        abe.store.commit()
                        page['body'] = ['<p>Your comment was updated.</p>\n']
                return
            else:
                javascript = """
            <script>
               function change_text(x){ 
                 x = x.replace(/!/g,"\\\\!");
                 x = x.replace(/\\n/g,"\\\\n");
                 x = x.replace(/\\$/g,"\\\\$");
                 document.getElementById("stext").innerHTML=x; 
               }
               function onload(){
                 change_text(document.getElementById("text").value);
               }
            </script>
            """

                page['title'] = 'Annotate address'
                page['body'] = [
                    javascript, '<form id="form" action="', page['dotdot'],
                    'annotate">\n'
                    'Address:', address, '<br/><br/>\n'
                    'Message:<br/><textarea id="text" onkeyup="change_text(this.value);" name="comment" cols="80" value=""></textarea><br/><br/>\n'
                    'You must sign your message with the addresses.<br/>\n'
                    'The signature will be returned by the following command line:<br/>\n'
                    '<pre>bitcoind signmessage <span id="saddress">' +
                    address +
                    '</span> "<span id="stext">your text</span>"</pre>\n'
                    'Signature:<br/><input name="signature" value="" style="width:500px;"/><br/>'
                    '<input name="address" type="hidden" value="' + address +
                    '" />'
                    '<button type="submit">Submit</button>\n'
                    '</form>\n'
                ]
Beispiel #34
0
    def handle_thresholdRelease(abe, page):
        page['title'] = 'Threshold Release'
        chain = abe.get_default_chain()

        target = (page['params'].get('target') or [''])[0]
        address = (page['params'].get('address') or [''])[0]
        secret = (page['params'].get('secret') or [''])[0]
        signature = (page['params'].get('signature') or [''])[0]

        if address:
            # check if address is valid
            version, binaddr = decode_check_address(address)
            if binaddr is None:
                page['body'] = ['<p>Not a valid address.</p>']
                return
            # check amount
            try:
                target = float(target)
            except:
                page['body'] = ['<p>Not a valid amount.</p>']
                return
            # check signature
            import bitcoinrpc
            conn = bitcoinrpc.connect_to_local()
            print address, signature
            try:
                v = conn.verifymessage(address, signature, "fundraiser")
            except:
                v = False
            if not v:
                page['body'] = ['<p>Invalid signature.</p>']
                return

            # little bobby tables
            secret = secret.replace('"', '\\"').replace("'", "\\'")
            # escape html
            #message = escape( message )
            #
            secret = secret[:1024]

            row = abe.store.selectrow(
                "select address from fundraisers where address='%s'" %
                (address))
            if not row:
                abe.store.sql(
                    "insert into fundraisers (address, target, secret) VALUES ('%s', %d, '%s')"
                    % (address, target, secret))
                abe.store.commit()
                page['body'] = [
                    '<p>Your fundraiser was added successfully.</p>\n'
                ]
            else:
                if not secret:
                    abe.store.sql(
                        "delete from fundraisers where address='%s'" %
                        (address))
                    abe.store.commit()
                    page['body'] = ['<p>Fundraiser entry was deleted.</p>\n']
                else:
                    abe.store.sql(
                        "update fundraisers set target=%d, secret='%s' where address='%s'"
                        % (target, secret, address))
                    abe.store.commit()
                    page['body'] = [
                        '<p>Your fundraiser data was updated.</p>\n'
                    ]

            msg = "<object data=\"http://ecdsa.org/fundraiser/" + address + "?width=400\" height=\"60\" width=\"400\">Donate to " + address + "</object/>"

            page['body'] += "Sample code:<br/><pre>" + escape(
                msg) + "</pre><br/><br/>" + msg
            return
        else:
            javascript = """
            <script>
               function change_address(x){ 
                 //check validity here
                 document.getElementById("saddress").innerHTML=x;
               }
               function onload(){
                 change_address(document.getElementById("address").value);
               }
            </script>
            """
            msg = """
This service allows you to release digital content when a requested amount of Bitcoin donations has been reached.<br/>
<br/>
For example, you may want to publish a low quality version of a music file, and release a high quality version only if donations reach the price you want.<br/>
<br/>
There are various ways to use this service:
<ul>
<li>You may upload your content at a private URL; we will disclose the URL once the amount is reached.</li>
<li>You may encrypt your content and upload it to a public server; we will publish the encryption password only when the target amount is reached.</li>
</ul>
Once the threshold is reached, the content is displayed in place of the donation progress bar.<br/>
<br/>
"""

            page['title'] = 'Threshold Release'
            page['body'] = [
                javascript, msg, '<form id="form" action="', page['dotdot'],
                'thresholdRelease">\n'
                'Address:<br/><input name="address" value="" style="width:500px;" onkeyup="change_address(this.value);"/><br/><br/>'
                'Target amount:<br/><input name="target" value="" style="width:500px;"/><br/><br/>'
                'Secret (will be displayed in place of the widget when the donation target is reached. Html, max. 1024 bytes):<br/>'
                '<textarea name="secret" value="" style="width:500px;"></textarea><br/><br/>'
                'You must provide a signature in order to demonstrate that you own the bitcoin address of the fundraiser.<br/>'
                'The signature will be returned by the following command line:<br/>\n'
                '<pre>bitcoind signmessage <span id="saddress"></span> <span id="stext">fundraiser</span></pre>\n'
                'Signature:<br/><input name="signature" value="" style="width:500px;"/><br/>'
                '<button type="submit">Submit</button>\n'
                '</form>\n'
            ]
Beispiel #35
0
sys.path.append('../src')

import bitcoinrpc
# from bitcoinrpc.exceptions import BitcoinException, InsufficientFunds

from decimal import Decimal

if __name__ == "__main__":

    from bitcoinrpc.config import read_default_config
    cfg = read_default_config(None)
    port = int(cfg.get('rpcport', '18332' if cfg.get('testnet') else '8332'))
    rpcuser = cfg.get('rpcuser', '')

    local_conn = bitcoinrpc.connect_to_local()  # will use read_default_config
    remote_conn = bitcoinrpc.connect_to_remote(user=rpcuser,
                                               password=cfg['rpcpassword'],
                                               host='localhost',
                                               port=port,
                                               use_https=False)

    for conn in (local_conn, remote_conn):
        assert (conn.getinfo().testnet)  # don't test on prodnet

        assert (type(conn.getblockcount()) is int)
        assert (type(conn.getconnectioncount()) is int)
        assert (type(conn.getdifficulty()) is Decimal)
        assert (type(conn.getgenerate()) is bool)
        conn.setgenerate(True)
        conn.setgenerate(True, 2)
Beispiel #36
0
if __name__ == "__main__":

    if args.config:
        from bitcoinrpc.config import read_config_file

        cfg = read_config_file(args.config)
    else:
        from bitcoinrpc.config import read_default_config

        cfg = read_default_config(None)
    port = int(cfg.get("rpcport", "18332" if cfg.get("testnet") else "8332"))
    rpcuser = cfg.get("rpcuser", "")

    connections = []
    if not args.nolocal:
        local_conn = bitcoinrpc.connect_to_local()  # will use read_default_config
        connections.append(local_conn)
    if not args.noremote:
        remote_conn = bitcoinrpc.connect_to_remote(
            user=rpcuser, password=cfg["rpcpassword"], host="localhost", port=port, use_https=False
        )
        connections.append(remote_conn)

    for conn in connections:
        assert conn.getinfo().testnet  # don't test on prodnet

        assert type(conn.getblockcount()) is int
        assert type(conn.getconnectioncount()) is int
        assert type(conn.getdifficulty()) is Decimal
        assert type(conn.getgenerate()) is bool
        conn.setgenerate(True)
Beispiel #37
0
 def __init__(self, address):
     super(BTCWallet, self).__init__(currency='btc')
     self.conn = bitcoinrpc.connect_to_local()
Beispiel #38
0
from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login, logout

from forms import CommentForm
from itertools import ifilter
from models import *
import bitcoinrpc
conn = bitcoinrpc.connect_to_local()  #need to have a configuration file specified and need site_packages/bitcoinrpc/read_default_config() to look at config file
#how do i connect to a remote wallet (to pay users)
'''
add posts
ways to vote
ways to sort posts by 'upvotes'
create a user
change/update password

'''

def logout_view(request):
    logout(request)
    return redirect('myapp.views.index')
    

def profile(request):
    if request.user.is_authenticated():
         logged_in=True
         account_string=str(request.user)
         '''
         #shows balance on my local wallet
         bal_msg= "Your balance is %f" % (conn.getbalance(),)
         #validating an address
Beispiel #39
0
    def handle_thresholdRelease(abe, page):
        page['title'] =  'Threshold Release'
        chain = abe.get_default_chain()

        target = (page['params'].get('target') or [''])[0]
        address = (page['params'].get('address') or [''])[0]
        secret   = (page['params'].get('secret') or [''])[0]
        signature = (page['params'].get('signature') or [''])[0]
        
        if address:
            # check if address is valid
            version, binaddr = decode_check_address(address)
            if binaddr is None:
                page['body'] = ['<p>Not a valid address.</p>']
                return
            # check amount
            try:
                target = float(target)
            except:
                page['body'] = ['<p>Not a valid amount.</p>']
                return
            # check signature
            import bitcoinrpc
            conn = bitcoinrpc.connect_to_local()
            print address, signature
            try:
                v = conn.verifymessage(address,signature, "fundraiser")
            except:
                v = False
            if not v:
                page['body'] = ['<p>Invalid signature.</p>']
                return

            # little bobby tables
            secret = secret.replace('"', '\\"').replace("'", "\\'")
            # escape html 
            #message = escape( message )
            #
            secret = secret[:1024]

            row = abe.store.selectrow("select address from fundraisers where address='%s'"%(address ) )
            if not row:
                abe.store.sql("insert into fundraisers (address, target, secret) VALUES ('%s', %d, '%s')"%( address, target, secret) )
                abe.store.commit()
                page['body'] = ['<p>Your fundraiser was added successfully.</p>\n']
            else:
                if not secret:
                    abe.store.sql("delete from fundraisers where address='%s'"%( address ) )
                    abe.store.commit()
                    page['body'] = ['<p>Fundraiser entry was deleted.</p>\n']
                else:
                    abe.store.sql("update fundraisers set target=%d, secret='%s' where address='%s'"%( target, secret, address ) )
                    abe.store.commit()
                    page['body'] = ['<p>Your fundraiser data was updated.</p>\n']

            msg = "<object data=\"http://ecdsa.org/fundraiser/"+address+"?width=400\" height=\"60\" width=\"400\">Donate to "+address+"</object/>"

            page['body'] += "Sample code:<br/><pre>"+escape(msg)+"</pre><br/><br/>"+msg
            return
        else:
            javascript = """
            <script>
               function change_address(x){ 
                 //check validity here
                 document.getElementById("saddress").innerHTML=x;
               }
               function onload(){
                 change_address(document.getElementById("address").value);
               }
            </script>
            """
            msg= """
This service allows you to release digital content when a requested amount of Bitcoin donations has been reached.<br/>
<br/>
For example, you may want to publish a low quality version of a music file, and release a high quality version only if donations reach the price you want.<br/>
<br/>
There are various ways to use this service:
<ul>
<li>You may upload your content at a private URL; we will disclose the URL once the amount is reached.</li>
<li>You may encrypt your content and upload it to a public server; we will publish the encryption password only when the target amount is reached.</li>
</ul>
Once the threshold is reached, the content is displayed in place of the donation progress bar.<br/>
<br/>
"""

            page['title'] = 'Threshold Release'
            page['body'] = [
                javascript, msg,
                '<form id="form" action="', page['dotdot'], 'thresholdRelease">\n'
                'Address:<br/><input name="address" value="" style="width:500px;" onkeyup="change_address(this.value);"/><br/><br/>'
                'Target amount:<br/><input name="target" value="" style="width:500px;"/><br/><br/>'
                'Secret (will be displayed in place of the widget when the donation target is reached. Html, max. 1024 bytes):<br/>'
                '<textarea name="secret" value="" style="width:500px;"></textarea><br/><br/>'
                'You must provide a signature in order to demonstrate that you own the bitcoin address of the fundraiser.<br/>'
                'The signature will be returned by the following command line:<br/>\n'
                '<pre>bitcoind signmessage <span id="saddress"></span> <span id="stext">fundraiser</span></pre>\n'
                'Signature:<br/><input name="signature" value="" style="width:500px;"/><br/>'
                '<button type="submit">Submit</button>\n'
                '</form>\n'
                ]
Beispiel #40
0
    def handle_annotate(abe, page):
        tx_hash = (page['params'].get('tx') or [''])[0]
        address = (page['params'].get('address') or [''])[0]
        message = (page['params'].get('comment') or [''])[0]
        signature = (page['params'].get('signature') or [''])[0]

        if not tx_hash and not address:
            page['title'] =  'Annotations'
            page['body'] += [ 'This website allows you to annotate the Bitcoin blockchain.<br/><br/>',
                              'You will need a version of bitcoind that has the "signmessage" command.<br/>'
                              'In order to annotate an address or transaction, first <a href="search">find</a> the corresponding page, then follow the "[+]" link. <a href="http://ecdsa.org/annotate?tx=e357fece18a4191be8236570c7dc309ec6ac04473317320b5e8b9ab7cd023549">(example here)</a><br/><br/>']
            
            page['body'] += [ '<h3>Annotated addresses.</h3>']
            rows = abe.store.selectall("""select text, address from addr_comments limit 100""" )
            page['body'] += [ '<table>']
            page['body'] += [ '<tr><th>Address</th><th>Comment</th></tr>']
            for row in rows:
                link = '<a href="address/' + row[1]+ '">'+ row[1] + '</a>'
                page['body'] += ['<tr><td>'+link+'</td><td>'+row[0]+'</td></tr>']
            page['body'] += [ '</table>']


            page['body'] += [ '<h3>Annotated transactions.</h3>']
            rows = abe.store.selectall("""select tx.tx_id, tx.tx_hash, comments.c_text 
                                          from comments left join tx on tx.tx_id = comments.c_tx where c_sig != '' limit 100""" )
            page['body'] += [ '<table>']
            page['body'] += [ '<tr><th>Transaction</th><th>Comment</th></tr>']
            for row in rows:
                link = '<a href="tx/' + row[1]+ '">'+ row[1] + '</a>'
                page['body'] += ['<tr><td>'+link+'</td><td>'+row[2]+'</td></tr>']
            page['body'] += [ '</table>']
            return

        if tx_hash:

            page['title'] =  'Annotate transaction'
            tx_id, b, c, d = abe.get_tx( tx_hash )
            chain = abe.get_default_chain()

            in_addresses = []
            for row in abe.get_tx_inputs( tx_id ):
                addr =  abe.store.binout(row[6])
                addr = hash_to_address_link(chain['address_version'], addr, '../')
                in_addresses.append( addr[3] )
            if not address:
                address = in_addresses[0]

            out_addresses = []
            for row in abe.get_tx_outputs( tx_id ):
                addr =  abe.store.binout(row[6])
                addr = hash_to_address_link(chain['address_version'], addr, '../')
                out_addresses.append( addr[3] )

            if message or signature:
                # check address
                #if address not in in_addresses and address not in out_addresses:
                if address not in in_addresses:
                    page['title'] = 'Error'
                    page['body'] = ['<p>wrong address for this transaction.</p>\n']
                    print address, in_addresses
                    return

                # check signature
                import bitcoinrpc
                conn = bitcoinrpc.connect_to_local()
                message = message.replace("\r\n","\\n").replace("!","\\!").replace("$","\\$")
                print "verifymessage:", address, signature, repr(message)
                try:
                    v = conn.verifymessage(address,signature, tx_hash+":"+message)
                except:
                    v = False
                if not v:
                    page['title'] = 'Error'
                    page['body'] = ['<p>Invalid signature.</p>']
                    return

                # little bobby tables
                message = message.replace('"', '\\"').replace("'", "\\'")
                # escape html 
                message = escape( message )
                message = message[:1024]

                row = abe.store.selectrow("select c_tx from comments where c_tx=%d "%(tx_id ) )
                if not row:
                    abe.store.sql("insert into comments (c_tx, c_text, c_pubkey, c_sig) VALUES (%d, '%s', '%s', '%s')"%( tx_id, message, address, signature) )
                    abe.store.commit()
                    page['body'] = ['<p>Your comment was added successfully.</p>\n']
                else:
                    if not message:
                        abe.store.sql("delete from comments where c_tx=%d "%( tx_id ) )
                        abe.store.commit()
                        page['body'] = ['<p>Your comment was deleted.</p>\n']
                    else:
                        abe.store.sql("update comments set c_text='%s', c_sig='%s', c_pubkey='%s' where c_tx=%d "%( message, signature, address, tx_id ) )
                        abe.store.commit()
                        page['body'] = ['<p>Your comment was updated.</p>\n']
                return
            else:
                select = "<select id=\"address\" onkeyup=\"change_address(this.value);\" onchange=\"change_address(this.value);\" name='address'>" \
                    + "\n".join( map( lambda addr: "<option value=\""+addr+"\">"+addr+"</option>", in_addresses ) ) \
                    +"</select>"
                select = select.replace("<option value=\""+address+"\">","<option value=\""+address+"\" selected>")
                tx_link = '<a href="tx/' + tx_hash + '">'+ tx_hash + '</a>'

                javascript = """
            <script>
               function change_address(x){ 
                 document.getElementById("saddress").innerHTML=x;
               }
               function change_text(x){ 
                 x = x.replace(/!/g,"\\\\!");
                 x = x.replace(/\\n/g,"\\\\n");
                 x = x.replace(/\\$/g,"\\\\$");
                 document.getElementById("stext").innerHTML = x; 
               }
               function onload(){
                 change_text(document.getElementById("text").value);
                 //change_address(document.getElementById("address").value);
               }
            </script>
            """

                page['title'] = 'Annotate transaction'
                page['body'] = [
                    javascript,
                    '<form id="form" action="', page['dotdot'], 'annotate">\n'
                    'Transaction: ',tx_link,'<br/>'
                    'Address:', select,'<br/><br/>\n'
                    'Message:<br/><textarea id="text" onkeyup="change_text(this.value);" name="comment" cols="80" value=""></textarea><br/><br/>\n'
                    'You must sign your message with one of the input addresses of involved in the transaction.<br/>\n'
                    'The signature will be returned by the following command line:<br/>\n'
                    '<pre>bitcoind signmessage <span id="saddress">'+in_addresses[0]+'</span> "'+tx_hash+':<span id="stext">your text</span>"</pre>\n'
                    'Signature:<br/><input name="signature" value="" style="width:500px;"/><br/>'
                    '<input name="tx" type="hidden" value="'+tx_hash+'" />'
                    '<button type="submit">Submit</button>\n'
                    '</form>\n']
            return
        

    
        if address:
            page['title'] =  'Annotate address'

            if message or signature:
                # check signature
                import bitcoinrpc
                conn = bitcoinrpc.connect_to_local()
                message = message.replace("\n","\\n").replace("!","\\!").replace("$","\\$")
                print "verifymessage:", address, signature, message
                try:
                    v = conn.verifymessage(address,signature, message)
                except:
                    v = False
                if not v:
                    page['title'] = 'Error'
                    page['body'] = ['<p>Invalid signature.</p>']
                    return

                # little bobby tables
                message = message.replace('"', '\\"').replace("'", "\\'")
                # escape html 
                message = escape( message )
                message = message[:1024]

                row = abe.store.selectrow("select address from addr_comments where address='%s' "%(address ) )
                if not row:
                    abe.store.sql("insert into addr_comments (address, text) VALUES ('%s', '%s')"%( address, message) )
                    abe.store.commit()
                    page['body'] = ['<p>Your comment was added successfully.</p>\n']
                else:
                    if not message:
                        abe.store.sql("delete from addr_comments where address='%s' "%( message ) )
                        abe.store.commit()
                        page['body'] = ['<p>Your comment was deleted.</p>\n']
                    else:
                        abe.store.sql("update addr_comments set text='%s' where address='%s' "%( message, address ) )
                        abe.store.commit()
                        page['body'] = ['<p>Your comment was updated.</p>\n']
                return
            else:
                javascript = """
            <script>
               function change_text(x){ 
                 x = x.replace(/!/g,"\\\\!");
                 x = x.replace(/\\n/g,"\\\\n");
                 x = x.replace(/\\$/g,"\\\\$");
                 document.getElementById("stext").innerHTML=x; 
               }
               function onload(){
                 change_text(document.getElementById("text").value);
               }
            </script>
            """

                page['title'] = 'Annotate address'
                page['body'] = [
                    javascript,
                    '<form id="form" action="', page['dotdot'], 'annotate">\n'
                    'Address:', address,'<br/><br/>\n'
                    'Message:<br/><textarea id="text" onkeyup="change_text(this.value);" name="comment" cols="80" value=""></textarea><br/><br/>\n'
                    'You must sign your message with the addresses.<br/>\n'
                    'The signature will be returned by the following command line:<br/>\n'
                    '<pre>bitcoind signmessage <span id="saddress">'+address+'</span> "<span id="stext">your text</span>"</pre>\n'
                    'Signature:<br/><input name="signature" value="" style="width:500px;"/><br/>'
                    '<input name="address" type="hidden" value="'+address+'" />'
                    '<button type="submit">Submit</button>\n'
                    '</form>\n']
 def __init__(self):
     print os.path.expanduser("~")+"/.litecoin/litecoin.conf"
     self.ltcconn = bitcoinrpc.connect_to_local(filename=os.path.expanduser("~")+"/.litecoin/litecoin.conf")
     litecoin_list_all_address = self.ltcconn.listreceivedbyaddress(0, True)
     all_address = []
     print litecoin_list_all_address
else:
    force=False

JSON = sys.stdin.readlines()

listOptions = json.loads(str(''.join(JSON)))

#Python environment issue, Some hex encoding doesn't respect this value properly
#Use either 21 or 41  (change if first tx hex created is invalid)
HEXSPACE='21'

#sort out whether using local or remote API
USER=getpass.getuser()

#sort out whether using local or remote API
conn = bitcoinrpc.connect_to_local()
try:
    conn.getblockcount()
except StandardError:
    try:
        with open('/home/'+USER+'/.bitcoin/bitcoin.conf') as fp:
            RPCPORT="8332"
            RPCHOST="localhost"
            for line in fp:
                #print line
                if line.split('=')[0] == "rpcuser":
                    RPCUSER=line.split('=')[1].strip()
                elif line.split('=')[0] == "rpcpassword":
                    RPCPASS=line.split('=')[1].strip()
                elif line.split('=')[0] == "rpcconnect":
                    RPCHOST=line.split('=')[1].strip()
def decode(rawhex, reference):

    #sort out whether using local or remote API
    conn = bitcoinrpc.connect_to_local()
    #conn = bitcoinrpc.connect_to_remote('btcrpc_username','btcrpc_secret',host='127.0.0.1', port=8332)

    rawBTC = conn.decoderawtransaction(rawhex)

    if reference == "":
        retval = {
            "Error": "Can\'t decode MP TX. No valid sending address found."
        }
        return {'Sender': reference, 'BTC': rawBTC, 'MP': retval}

    #get all multisigs
    multisig_output = []
    dest = ""
    for output in rawBTC['vout']:
        if output['scriptPubKey']['type'] == 'multisig':
            multisig_output.append(output)  #grab msigs
        elif output['scriptPubKey']['type'] in ['pubkeyhash', 'scripthash']:
            try:
                for address in output['scriptPubKey']['addresses']:
                    if address not in [
                            '1EXoDusjGwvnjZUyKkxZ4UHEf77z6A5S4P',
                            'mpexoDuSkGGqvqrkrjiFng38QPkJQVFyqv'
                    ] and address not in reference:
                        dest = address
                        #return on first successful dest address per spec (highest vout)
                        break
            except KeyError:
                pass

    #extract compressed keys
    scriptkeys = []
    for output in multisig_output:  #seqnums start at 1, so adjust range
        split_script = output['scriptPubKey']['asm'].split(' ')
        for val in split_script:
            if len(val) == 66:
                scriptkeys.append(val)

    #filter keys that are ref
    nonrefkeys = []

    #check for testnet addresses
    if reference[:1] in ['2', 'm', 'n']:
        #testnet address
        offset = 111
    else:
        offset = 0

    for compressedkey in scriptkeys:
        if pybitcointools.pubtoaddr(compressedkey, offset) not in reference:
            nonrefkeys.append(compressedkey)

    max_seqnum = len(nonrefkeys)
    sha_keys = [hashlib.sha256(reference).digest().encode('hex').upper()
                ]  #first sha256 of ref addr, see class B for more info
    for i in range(max_seqnum):
        if i < (max_seqnum - 1):
            sha_keys.append(
                hashlib.sha256(sha_keys[i]).digest().encode(
                    'hex').upper())  #keep sha'ing to generate more packets

    pairs = []
    for i in range(len(nonrefkeys)):
        pairs.append((nonrefkeys[i], sha_keys[i]))

    packets = []
    for pair in pairs:
        obpacket = pair[0].upper()[2:-2]
        shaaddress = pair[1][:-2]
        print 'Obfus/SHA', obpacket, shaaddress
        datapacket = ''
        for i in range(len(obpacket)):
            if obpacket[i] == shaaddress[i]:
                datapacket = datapacket + '0'
            else:
                bin_ob = int('0x' + obpacket[i], 16)
                bin_sha = int('0x' + shaaddress[i], 16)
                xored = hex(bin_ob ^ bin_sha)[2:].upper()
                datapacket = datapacket + xored
        packets.append(datapacket)

    long_packet = ''
    for packet in packets:
        print 'Decoded packet #' + str(packet[0:2]) + ' : ' + packet
        long_packet += packet[2:]

    retval = ""
    #DEBUG print long_packet[4:8]

    if long_packet[4:8] == '0032':
        #Create Fixed Issuance
        spare_bytes = ''.join(long_packet[22:])
        #DEBUG print spare_bytes.split('00')
        len_var_fields = len(''.join(spare_bytes.split('00')[0:5]) +
                             '0000000000')
        #DEBUG print len_var_fields, spare_bytes[len_var_fields:len_var_fields+16],spare_bytes

        retval = {
            'TxVersion':
            int(long_packet[0:4], 16),
            'TxType':
            int(long_packet[4:8], 16),
            'TxTypeString':
            'Create Fixed Issuance',
            'Ecosystem':
            int(long_packet[8:10], 16),
            'Property Type':
            int(long_packet[10:14], 16),
            'Previous Property ID':
            int(long_packet[14:22], 16),
            'Property Category':
            spare_bytes.split('00')[0].decode('hex'),
            'Property Subcategory':
            spare_bytes.split('00')[1].decode('hex'),
            'Property Name':
            spare_bytes.split('00')[2].decode('hex'),
            'Property URL':
            spare_bytes.split('00')[3].decode('hex'),
            'Property Data':
            ''.join(spare_bytes.split('00')[4]).decode('hex'),
            'Number of Properties: ':
            int(str(int(spare_bytes[len_var_fields:len_var_fields + 16], 16)))
        }

    if long_packet[4:8] == '0033':
        #Create Variable issuance (Crowdsale)
        spare_bytes = ''.join(long_packet[22:])
        #DEBUG print spare_bytes.split('00')
        len_var_fields = len(''.join(spare_bytes.split('00')[0:5]) +
                             '0000000000')
        #DEBUG print len_var_fields, spare_bytes[len_var_fields:len_var_fields+16],spare_bytes

        retval = {
            'TxVersion':
            int(long_packet[0:4], 16),
            'TxType':
            int(long_packet[4:8], 16),
            'TxTypeString':
            'Create Variable Issuance (Crowdsale)',
            'Ecosystem':
            int(long_packet[8:10], 16),
            'Property Type':
            int(long_packet[10:14], 16),
            'Previous Property ID':
            int(long_packet[14:22], 16),
            'Property Category':
            spare_bytes.split('00')[0].decode('hex'),
            'Property Subcategory':
            spare_bytes.split('00')[1].decode('hex'),
            'Property Name':
            spare_bytes.split('00')[2].decode('hex'),
            'Property URL':
            spare_bytes.split('00')[3].decode('hex'),
            'Property Data':
            ''.join(spare_bytes.split('00')[4]).decode('hex'),
            'PropertyID Desired':
            str(int(spare_bytes[len_var_fields:len_var_fields + 8], 16)),
            'Number of Properties':
            str(
                int(spare_bytes[len_var_fields + 8:len_var_fields + 8 + 16],
                    16)),
            'Deadline':
            str(
                int(
                    spare_bytes[len_var_fields + 8 + 16:len_var_fields + 8 +
                                16 + 16], 16)),
            'Earlybird Bonus':
            str(
                int(
                    spare_bytes[len_var_fields + 8 + 16 + 16:len_var_fields +
                                8 + 16 + 16 + 2], 16)),
            'Percentage for Issuer':
            str(
                int(
                    spare_bytes[len_var_fields + 8 + 16 + 16 +
                                2:len_var_fields + 8 + 16 + 16 + 2 + 2], 16))
        }

    if long_packet[4:8] == '0000':
        #simple send
        retval = {
            'TxVersion': int(long_packet[0:4], 16),
            'TxType': int(long_packet[4:8], 16),
            'TxTypeString': 'Simple Send',
            'PropertyID': int(long_packet[8:16], 16),
            'Amount': int(long_packet[16:32], 16)
        }

    if long_packet[4:8] == '0003':
        #STO
        retval = {
            'TxVersion': int(long_packet[0:4], 16),
            'TxType': int(long_packet[4:8], 16),
            'TxTypeString': 'Send To Owners',
            'PropertyID': int(long_packet[8:16], 16),
            'Amount': int(long_packet[16:32], 16)
        }

    if long_packet[4:8] == '0014':
        #DEx Sell Offer
        retval = {
            'TxVersion': int(long_packet[0:4], 16),
            'TxType': int(long_packet[4:8], 16),
            'TxTypeString': 'DEx Sell Offer',
            'PropertyID': int(long_packet[8:16], 16),
            'Amount': int(long_packet[16:32], 16),
            'BTCDesired': int(long_packet[32:48], 16),
            'TimePeriod': int(long_packet[48:50], 16),
            'FeeRequired': int(long_packet[50:66], 16),
            'Action': int(long_packet[66:68], 16)
        }

    if long_packet[4:8] == '0035':
        #Close Crowdsale Manually
        retval = {
            'TxVersion': int(long_packet[0:4], 16),
            'TxType': int(long_packet[4:8], 16),
            'TxTypeString': 'Close Crowdsale Manually',
            'PropertyID': int(long_packet[8:16], 16)
        }

    if long_packet[4:8] == '0036':
        #grant properties
        #Create Fixed Issuance
        spare_bytes = ''.join(long_packet[22:])
        #DEBUG print spare_bytes.split('00')
        len_var_fields = len(''.join(spare_bytes.split('00')[0:5]) +
                             '0000000000')
        #DEBUG print len_var_fields, spare_bytes[len_var_fields:len_var_fields+16],spare_bytes

        retval = {
            'TxVersion': int(long_packet[0:4], 16),
            'TxType': int(long_packet[4:8], 16),
            'TxTypeString': 'Create New Grant Property',
            'Ecosystem': int(long_packet[8:10], 16),
            'Property Type': int(long_packet[10:14], 16),
            'Previous Property ID': int(long_packet[14:22], 16),
            'Property Category': spare_bytes.split('00')[0].decode('hex'),
            'Property Subcategory': spare_bytes.split('00')[1].decode('hex'),
            'Property Name': spare_bytes.split('00')[2].decode('hex'),
            'Property URL': spare_bytes.split('00')[3].decode('hex'),
            'Property Data': ''.join(spare_bytes.split('00')[4]).decode('hex')
        }
        #'Number of Properties: ': int(str(int(spare_bytes[len_var_fields:len_var_fields+16],16)))

    if long_packet[4:8] == '0037':
        #grant properties
        retval = {
            'TxVersion': int(long_packet[0:4], 16),
            'TxType': int(long_packet[4:8], 16),
            'TxTypeString': 'Grant Properties',
            'PropertyID': int(long_packet[8:16], 16),
            'Amount': int(long_packet[16:32], 16)
        }

    if long_packet[4:8] == '0038':
        #revoke properties
        retval = {
            'TxVersion': int(long_packet[0:4], 16),
            'TxType': int(long_packet[4:8], 16),
            'TxTypeString': 'Revoke Properties',
            'PropertyID': int(long_packet[8:16], 16),
            'Amount': int(long_packet[16:32], 16)
        }

    if retval == "":
        retval = {"Error": "Can\'t decode MP TX"}
        dest = ""
    retval['sender'] = reference
    retval['recipient'] = dest

    print json.dumps(retval, indent=2)