#!/usr/bin/env python
#
# mmgen = Multi-Mode GENerator, command-line Bitcoin cold storage solution
# Copyright (C) 2013 by philemon <mmgen-py@yandex.com>
# 
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# 
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
"""
mmgen-txsign: Sign a Bitcoin transaction generated by mmgen-txcreate
"""

import sys
#from hashlib import sha256

from mmgen.Opts import *
from mmgen.license import *
from mmgen.config import *
from mmgen.tx import *
from mmgen.utils import check_opts, msg, user_confirm, check_infile, get_lines_from_file, my_getpass, my_raw_input

prog_name = sys.argv[0].split("/")[-1]

help_data = {
	'prog_name': prog_name,
	'desc':    "Sign a Bitcoin transaction generated by mmgen-txcreate",
	'usage':   "[opts] <transaction file>",
	'options': """
-h, --help               Print this help message
-d, --outdir          d  Specify an alternate directory 'd' for output
-e, --echo-passphrase    Print passphrase to screen when typing it
-i, --info               Display information about the transaction and exit
-q, --quiet              Suppress warnings; overwrite files without asking
"""
}

short_opts = "hd:eiq"
long_opts  = "help","outdir=","echo_passphrase","info","quiet"

opts,cmd_args = process_opts(sys.argv,help_data,short_opts,long_opts)

# Exits on invalid input
check_opts(opts, ('outdir',))

if debug:
	print "Processed options:     %s" % repr(opts)
	print "Cmd args:              %s" % repr(cmd_args)

if len(cmd_args) == 1:
	infile = cmd_args[0]
	check_infile(infile)
else: usage(help_data)

# Begin execution

c = connect_to_bitcoind()

tx_data = get_lines_from_file(infile,"transaction data")

metadata,tx_hex,sig_data,inputs_data =  parse_tx_data(tx_data)

if 'info' in opts:
	view_tx_data(c,inputs_data,tx_hex,metadata)
	sys.exit(0)

if not 'quiet' in opts and not 'info' in opts: do_license_msg()

msg("Successfully opened transaction file '%s'" % infile)

if user_confirm("View transaction data? ",default_yes=False):
	view_tx_data(c,inputs_data,tx_hex,metadata)

prompt = "Enter passphrase for bitcoind wallet: "
if 'echo_passphrase' in opts:
	password = my_raw_input(prompt)
else:
	password = my_getpass(prompt)

wallet_enc = True
from bitcoinrpc import exceptions

try:
	c.walletpassphrase(password, 9999)
except exceptions.WalletWrongEncState:
	msg("Wallet is unencrypted")
	wallet_enc = False
except exceptions.WalletPassphraseIncorrect:
	msg("Passphrase incorrect")
	sys.exit(3)
except exceptions.WalletAlreadyUnlocked:
	msg("WARNING: Wallet already unlocked!")
else:
	msg("Passphrase OK")

try:
	sig_tx = c.signrawtransaction(tx_hex,sig_data)
#	sig_tx = {'hex':"deadbeef0123456789ab",'complete':True}
except:
	msg("Failed to sign transaction")
	if wallet_enc:
		c.walletlock()
		msg("Locking wallet")
	sys.exit(3)

if wallet_enc:
	c.walletlock()
	msg("Locking wallet")

if sig_tx['complete']:
	msg("Signing completed")
else:
	msg("Signing failed: 'complete=%s'" % sig_tx['complete'])
	sys.exit(3)

prompt = "Save signed transaction?"
if user_confirm(prompt,default_yes=True):
	print_signed_tx_to_file(tx_hex,sig_tx['hex'],metadata,opts)