#!/usr/bin/env python
# Pynstawallet 2: Python binding to Instawallet API
# by Multiversum
# Improvements:
# - ability to create new wallet from a passphrase
# - ability to get balance in BTC, not only Satoshis

from requests import get, post
from hashlib import sha256
from base64 import b64encode

instaweb_base = r'https://www.instawallet.org'
instaapi_base = instaweb_base + r'/api/v1'

def btcaddress(walletid):
	''' Get Bitcoin address associated with private wallet ID '''
	resp = get(instaapi_base+'/w/'+walletid+'/address').json
	if resp:
		return resp['address']
	else:
		return None

def passtoid(passphrase):
	''' Convert (hash) your passphrase or password to the private Instawallet ID '''
	preid = b64encode(sha256(passphrase).digest()).strip('/=\\+')
	return filter(lambda x: x not in '/=\\+', preid)

def new_wallet(passphrase=None):
	''' Create a new wallet (automatically or from passphrase) and return its private wallet ID and public bitcoin address '''
	if passphrase:
		walletid = passtoid(passphrase)
		resp = get(instaweb_base+'/w/'+walletid)
		return walletid, btcaddress(walletid)
	else:
		resp = post(instaapi_base+'/new_wallet').json
		if resp:
			walletid = resp['wallet_id']
			return walletid, btcaddress(walletid)
		else:
			return None

def balance(walletid):
	''' Get your Instawallet balance in Satoshis by private wallet ID '''
	resp = get(instaapi_base+'/w/'+walletid+'/balance').json
	if resp:
		return resp['balance']
	else:
		return None
		
def btcbalance(walletid):
	''' Get your Instawallet balance in Bitcoins by private wallet ID '''
	satbalance = balance(walletid)
	if satbalance is not None:
		return satbalance/float(100000000.)
	else:
		return None
		
def pay(walletid, dest_addr, amount):
	''' Initiate a payment from wallet ID to destination Bitcoin address.
	The payment amount is in Satoshis.
	The function returns operation result code and message. '''
	params = { 'address' : dest_addr, 'amount' : amount }
	resp = post(instaapi_base+'/w/'+walletid+'/payment', data=params).json
	if resp:
		return resp['message_code'], resp['message']
	else:
		return -1, 'Unknown error'