tx.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415
  1. #!/usr/bin/env python
  2. #
  3. # mmgen = Multi-Mode GENerator, command-line Bitcoin cold storage solution
  4. # Copyright (C)2013-2016 Philemon <mmgen-py@yandex.com>
  5. #
  6. # This program is free software: you can redistribute it and/or modify
  7. # it under the terms of the GNU General Public License as published by
  8. # the Free Software Foundation, either version 3 of the License, or
  9. # (at your option) any later version.
  10. #
  11. # This program is distributed in the hope that it will be useful,
  12. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. # GNU General Public License for more details.
  15. #
  16. # You should have received a copy of the GNU General Public License
  17. # along with this program. If not, see <http://www.gnu.org/licenses/>.
  18. """
  19. tx.py: Bitcoin transaction routines
  20. """
  21. import sys,os
  22. from stat import *
  23. from binascii import unhexlify
  24. from mmgen.common import *
  25. from mmgen.obj import *
  26. def is_mmgen_seed_id(s): return SeedID(sid=s,on_fail='silent')
  27. def is_mmgen_idx(s): return AddrIdx(s,on_fail='silent')
  28. def is_mmgen_id(s): return MMGenID(s,on_fail='silent')
  29. def is_btc_addr(s): return BTCAddr(s,on_fail='silent')
  30. def is_b58_str(s):
  31. from mmgen.bitcoin import b58a
  32. return set(list(s)) <= set(b58a)
  33. def is_wif(s):
  34. if s == '': return False
  35. from mmgen.bitcoin import wif2hex
  36. return bool(wif2hex(s))
  37. class MMGenTxInputOldFmt(MMGenListItem): # for converting old tx files only
  38. tr = {'amount':'amt', 'address':'addr', 'confirmations':'confs','comment':'label'}
  39. attrs = 'txid','vout','amt','label','mmid','addr','confs','scriptPubKey','wif'
  40. attrs_priv = 'tr',
  41. class MMGenTxInput(MMGenListItem):
  42. attrs = 'txid','vout','amt','label','mmid','addr','confs','scriptPubKey','have_wif'
  43. label = MMGenListItemAttr('label','MMGenAddrLabel')
  44. class MMGenTxOutput(MMGenListItem):
  45. attrs = 'txid','vout','amt','label','mmid','addr','have_wif'
  46. label = MMGenListItemAttr('label','MMGenAddrLabel')
  47. class MMGenTX(MMGenObject):
  48. ext = 'rawtx'
  49. raw_ext = 'rawtx'
  50. sig_ext = 'sigtx'
  51. txid_ext = 'txid'
  52. desc = 'transaction'
  53. max_fee = BTCAmt('0.01')
  54. def __init__(self,filename=None):
  55. self.inputs = []
  56. self.inputs_enc = []
  57. self.outputs = []
  58. self.outputs_enc = []
  59. self.change_addr = ''
  60. self.size = 0 # size of raw serialized tx
  61. self.fee = BTCAmt('0')
  62. self.send_amt = BTCAmt('0') # total amt minus change
  63. self.hex = '' # raw serialized hex transaction
  64. self.label = MMGenTXLabel('')
  65. self.txid = ''
  66. self.btc_txid = ''
  67. self.timestamp = ''
  68. self.chksum = ''
  69. self.fmt_data = ''
  70. self.blockcount = 0
  71. if filename:
  72. if get_extension(filename) == self.sig_ext:
  73. self.mark_signed()
  74. self.parse_tx_file(filename)
  75. def add_output(self,btcaddr,amt): # 'txid','vout','amount','label','mmid','address'
  76. self.outputs.append(MMGenTxOutput(addr=btcaddr,amt=amt))
  77. def del_output(self,btcaddr):
  78. for i in range(len(self.outputs)):
  79. if self.outputs[i].addr == btcaddr:
  80. self.outputs.pop(i); return
  81. raise ValueError
  82. def sum_outputs(self):
  83. return BTCAmt(sum([e.amt for e in self.outputs]))
  84. def add_mmaddrs_to_outputs(self,ad_w,ad_f):
  85. a = [e.addr for e in self.outputs]
  86. d = ad_w.make_reverse_dict(a)
  87. d.update(ad_f.make_reverse_dict(a))
  88. for e in self.outputs:
  89. if e.addr and e.addr in d:
  90. e.mmid,f = d[e.addr]
  91. if f: e.label = f
  92. # def encode_io(self,desc):
  93. # tr = getattr((MMGenTxOutput,MMGenTxInput)[desc=='inputs'],'tr')
  94. # tr_rev = dict([(v,k) for k,v in tr.items()])
  95. # return [dict([(tr_rev[e] if e in tr_rev else e,getattr(d,e)) for e in d.__dict__])
  96. # for d in getattr(self,desc)]
  97. #
  98. def create_raw(self,c):
  99. i = [{'txid':e.txid,'vout':e.vout} for e in self.inputs]
  100. o = dict([(e.addr,e.amt) for e in self.outputs])
  101. self.hex = c.createrawtransaction(i,o)
  102. self.txid = make_chksum_6(unhexlify(self.hex)).upper()
  103. # returns true if comment added or changed
  104. def add_comment(self,infile=None):
  105. if infile:
  106. self.label = MMGenTXLabel(get_data_from_file(infile,'transaction comment'))
  107. else: # get comment from user, or edit existing comment
  108. m = ('Add a comment to transaction?','Edit transaction comment?')[bool(self.label)]
  109. if keypress_confirm(m,default_yes=False):
  110. while True:
  111. s = MMGenTXLabel(my_raw_input('Comment: ',insert_txt=self.label))
  112. if s:
  113. lbl_save = self.label
  114. self.label = s
  115. return (True,False)[lbl_save == self.label]
  116. else:
  117. msg('Invalid comment')
  118. return False
  119. def edit_comment(self):
  120. return self.add_comment(self)
  121. # https://bitcoin.stackexchange.com/questions/1195/how-to-calculate-transaction-size-before-sending
  122. def calculate_size_and_fee(self,fee_estimate):
  123. self.size = len(self.inputs)*180 + len(self.outputs)*34 + 10
  124. if fee_estimate:
  125. ftype,fee = 'Calculated',fee_estimate*opt.tx_fee_adj*self.size / 1024
  126. else:
  127. ftype,fee = 'User-selected',opt.tx_fee
  128. ufee = None
  129. if not keypress_confirm('{} TX fee is {} BTC. OK?'.format(ftype,fee.hl()),default_yes=True):
  130. while True:
  131. ufee = my_raw_input('Enter transaction fee: ')
  132. if BTCAmt(ufee,on_fail='return'):
  133. ufee = BTCAmt(ufee)
  134. if ufee > self.max_fee:
  135. msg('{} BTC: fee too large (maximum fee: {} BTC)'.format(ufee,self.max_fee))
  136. else:
  137. fee = ufee
  138. break
  139. self.fee = fee
  140. vmsg('Inputs:{} Outputs:{} TX size:{}'.format(
  141. len(self.inputs),len(self.outputs),self.size))
  142. vmsg('Fee estimate: {} (1024 bytes, {} confs)'.format(fee_estimate,opt.tx_confs))
  143. m = ('',' (after %sx adjustment)' % opt.tx_fee_adj)[opt.tx_fee_adj != 1 and not ufee]
  144. vmsg('TX fee: {}{}'.format(self.fee,m))
  145. # inputs methods
  146. def list_wifs(self,desc,mmaddrs_only=False):
  147. return [e.wif for e in getattr(self,desc) if e.mmid] if mmaddrs_only \
  148. else [e.wif for e in getattr(self,desc)]
  149. def delete_attrs(self,desc,attr):
  150. for e in getattr(self,desc):
  151. if hasattr(e,attr): delattr(e,attr)
  152. def decode_io(self,desc,data):
  153. io = (MMGenTxOutput,MMGenTxInput)[desc=='inputs']
  154. return [io(**dict([(k,d[k]) for k in io.attrs
  155. if k in d and d[k] not in ('',None)])) for d in data]
  156. def decode_io_oldfmt(self,data):
  157. io = MMGenTxInputOldFmt
  158. tr_rev = dict([(v,k) for k,v in io.tr.items()])
  159. copy_keys = [tr_rev[k] if k in tr_rev else k for k in io.attrs]
  160. return [io(**dict([(io.tr[k] if k in io.tr else k,d[k])
  161. for k in copy_keys if k in d and d[k] != ''])) for d in data]
  162. def copy_inputs_from_tw(self,data):
  163. self.inputs = self.decode_io('inputs',[e.__dict__ for e in data])
  164. def get_input_sids(self):
  165. return set([e.mmid[:8] for e in self.inputs if e.mmid])
  166. def sum_inputs(self):
  167. return sum([e.amt for e in self.inputs])
  168. def add_timestamp(self):
  169. self.timestamp = make_timestamp()
  170. def add_blockcount(self,c):
  171. self.blockcount = int(c.getblockcount())
  172. def format(self):
  173. from mmgen.bitcoin import b58encode
  174. lines = (
  175. '{} {} {} {}'.format(
  176. self.txid,
  177. self.send_amt,
  178. self.timestamp,
  179. self.blockcount
  180. ),
  181. self.hex,
  182. repr([e.__dict__ for e in self.inputs]),
  183. repr([e.__dict__ for e in self.outputs])
  184. ) + ((b58encode(self.label.encode('utf8')),) if self.label else ())
  185. self.chksum = make_chksum_6(' '.join(lines))
  186. self.fmt_data = '\n'.join((self.chksum,) + lines)+'\n'
  187. def get_non_mmaddrs(self,desc):
  188. return list(set([i.addr for i in getattr(self,desc) if not i.mmid]))
  189. # return true or false, don't exit
  190. def sign(self,c,tx_num_str,keys):
  191. if not keys:
  192. msg('No keys. Cannot sign!')
  193. return False
  194. qmsg('Passing %s key%s to bitcoind' % (len(keys),suf(keys,'k')))
  195. dmsg('Keys:\n %s' % '\n '.join(keys))
  196. sig_data = [dict([(k,getattr(d,k)) for k in 'txid','vout','scriptPubKey'])
  197. for d in self.inputs]
  198. dmsg('Sig data:\n%s' % pp_format(sig_data))
  199. dmsg('Raw hex:\n%s' % self.hex)
  200. msg_r('Signing transaction{}...'.format(tx_num_str))
  201. sig_tx = c.signrawtransaction(self.hex,sig_data,keys)
  202. if sig_tx['complete']:
  203. msg('OK')
  204. self.hex = sig_tx['hex']
  205. self.mark_signed()
  206. return True
  207. else:
  208. msg('failed\nBitcoind returned the following errors:')
  209. pp_msg(sig_tx['errors'])
  210. return False
  211. def mark_signed(self):
  212. self.desc = 'signed transaction'
  213. self.ext = self.sig_ext
  214. def check_signed(self,c):
  215. d = c.decoderawtransaction(self.hex)
  216. ret = bool(d['vin'][0]['scriptSig']['hex'])
  217. if ret: self.mark_signed()
  218. return ret
  219. def send(self,c,bogus=False):
  220. if bogus:
  221. self.btc_txid = 'deadbeef' * 8
  222. m = 'BOGUS transaction NOT sent: %s'
  223. else:
  224. self.btc_txid = c.sendrawtransaction(self.hex) # exits on failure?
  225. m = 'Transaction sent: %s'
  226. msg(m % self.btc_txid)
  227. def write_txid_to_file(self,ask_write=False,ask_write_default_yes=True):
  228. fn = '%s[%s].%s' % (self.txid,self.send_amt,self.txid_ext)
  229. write_data_to_file(fn,self.btc_txid+'\n','transaction ID',
  230. ask_write=ask_write,
  231. ask_write_default_yes=ask_write_default_yes)
  232. def write_to_file(self,add_desc='',ask_write=True,ask_write_default_yes=False):
  233. if ask_write == False:
  234. ask_write_default_yes=True
  235. self.format()
  236. fn = '%s[%s].%s' % (self.txid,self.send_amt,self.ext)
  237. write_data_to_file(fn,self.fmt_data,self.desc+add_desc,
  238. ask_write=ask_write,
  239. ask_write_default_yes=ask_write_default_yes)
  240. def view_with_prompt(self,prompt=''):
  241. prompt += ' (y)es, (N)o, pager (v)iew, (t)erse view'
  242. reply = prompt_and_get_char(prompt,'YyNnVvTt',enter_ok=True)
  243. if reply and reply in 'YyVvTt':
  244. self.view(pager=reply in 'Vv',terse=reply in 'Tt')
  245. def view(self,pager=False,pause=True,terse=False):
  246. o = self.format_view(terse=terse).encode('utf8')
  247. if pager: do_pager(o)
  248. else:
  249. sys.stdout.write(o)
  250. from mmgen.term import get_char
  251. if pause:
  252. get_char('Press any key to continue: ')
  253. msg('')
  254. def format_view(self,terse=False):
  255. try:
  256. blockcount = bitcoin_connection().getblockcount()
  257. except:
  258. blockcount = None
  259. fs = (
  260. 'TRANSACTION DATA\n\nHeader: [Tx ID: {}] [Amount: {} BTC] [Time: {}]\n\n',
  261. 'Transaction {} - {} BTC - {} UTC\n'
  262. )[bool(terse)]
  263. out = fs.format(self.txid,self.send_amt.hl(),self.timestamp)
  264. enl = ('\n','')[bool(terse)]
  265. if self.label:
  266. out += 'Comment: %s\n%s' % (self.label.hl(),enl)
  267. out += 'Inputs:\n' + enl
  268. nonmm_str = '(non-{pnm} address)'.format(pnm=g.proj_name)
  269. # for i in self.inputs: print i #DEBUG
  270. for n,e in enumerate(self.inputs):
  271. if blockcount:
  272. confs = e.confs + blockcount - self.blockcount
  273. days = int(confs * g.mins_per_block / (60*24))
  274. mmid_fmt = e.mmid.fmt(width=len(nonmm_str),encl='()',color=True) if e.mmid \
  275. else MMGenID.hlc(nonmm_str)
  276. if terse:
  277. out += '%3s: %s %s %s BTC' % (n+1, e.addr.fmt(color=True),mmid_fmt, e.amt.hl())
  278. else:
  279. for d in (
  280. (n+1, 'tx,vout:', '%s,%s' % (e.txid, e.vout)),
  281. ('', 'address:', e.addr.fmt(color=True) + ' ' + mmid_fmt),
  282. ('', 'comment:', e.label.hl() if e.label else ''),
  283. ('', 'amount:', '%s BTC' % e.amt.hl()),
  284. ('', 'confirmations:', '%s (around %s days)' % (confs,days) if blockcount else '')
  285. ):
  286. if d[2]: out += ('%3s %-8s %s\n' % d)
  287. out += '\n'
  288. out += 'Outputs:\n' + enl
  289. for n,e in enumerate(self.outputs):
  290. mmid_fmt = e.mmid.fmt(width=len(nonmm_str),encl='()',color=True) if e.mmid \
  291. else MMGenID.hlc(nonmm_str)
  292. if terse:
  293. out += '%3s: %s %s %s BTC' % (n+1, e.addr.fmt(color=True),mmid_fmt, e.amt.hl())
  294. else:
  295. for d in (
  296. (n+1, 'address:', e.addr.fmt(color=True) + ' ' + mmid_fmt),
  297. ('', 'comment:', e.label.hl() if e.label else ''),
  298. ('', 'amount:', '%s BTC' % e.amt.hl())
  299. ):
  300. if d[2]: out += ('%3s %-8s %s\n' % d)
  301. out += '\n'
  302. fs = (
  303. 'Total input: %s BTC\nTotal output: %s BTC\nTX fee: %s BTC\n',
  304. 'In %s BTC - Out %s BTC - Fee %s BTC\n'
  305. )[bool(terse)]
  306. total_in = self.sum_inputs()
  307. total_out = self.sum_outputs()
  308. out += fs % (
  309. total_in.hl(),
  310. total_out.hl(),
  311. (total_in-total_out).hl()
  312. )
  313. return out
  314. def parse_tx_file(self,infile):
  315. self.parse_tx_data(get_lines_from_file(infile,self.desc+' data'))
  316. def parse_tx_data(self,tx_data):
  317. err_str,err_fmt = '','Invalid %s in transaction file'
  318. if len(tx_data) == 6:
  319. self.chksum,metadata,self.hex,inputs_data,outputs_data,comment = tx_data
  320. elif len(tx_data) == 5:
  321. self.chksum,metadata,self.hex,inputs_data,outputs_data = tx_data
  322. comment = ''
  323. else:
  324. err_str = 'number of lines'
  325. if not err_str:
  326. if self.chksum != make_chksum_6(' '.join(tx_data[1:])):
  327. err_str = 'checksum'
  328. elif len(metadata.split()) != 4:
  329. err_str = 'metadata'
  330. else:
  331. self.txid,send_amt,self.timestamp,blockcount = metadata.split()
  332. self.send_amt = BTCAmt(send_amt)
  333. self.blockcount = int(blockcount)
  334. try: unhexlify(self.hex)
  335. except: err_str = 'hex data'
  336. else:
  337. try: self.inputs = self.decode_io('inputs',eval(inputs_data))
  338. except: err_str = 'inputs data'
  339. else:
  340. try: self.outputs = self.decode_io('outputs',eval(outputs_data))
  341. except: err_str = 'btc-to-mmgen address map data'
  342. else:
  343. if comment:
  344. from mmgen.bitcoin import b58decode
  345. comment = b58decode(comment)
  346. if comment == False:
  347. err_str = 'encoded comment (not base58)'
  348. else:
  349. self.label = MMGenTXLabel(comment,on_fail='return')
  350. if not self.label:
  351. err_str = 'comment'
  352. if err_str:
  353. msg(err_fmt % err_str)
  354. sys.exit(2)